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 | mit | b38cc868c25aeb17467c46a1cf57ca40021d9db5 | 0 | TheBrianiac/OtisArena | package me.otisdiver.otisarena;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import me.otisdiver.otisarena.event.JoinQuit;
import me.otisdiver.otisarena.event.GameDeath;
import me.otisdiver.otisarena.event.LobbyGuard;
import me.otisdiver.otisarena.event.StartingCanceller;
import me.otisdiver.otisarena.event.WorldGuard;
import me.otisdiver.otisarena.game.Game;
public class OtisArena extends JavaPlugin {
private Game game;
public void onEnable() {
// instantiate the game class
game = new Game(this);
// load the config
ConfigUtils.initiate(this);
// register event listeners
new JoinQuit(this);
new StartingCanceller(this);
new GameDeath(this);
new LobbyGuard(this);
new WorldGuard(this);
}
public void onDisable() {
// unload world
Bukkit.unloadWorld(game.getActiveWorld().getName(), false);
}
public Game getGame() {
return game;
}
}
| src/main/java/me/otisdiver/otisarena/OtisArena.java | package me.otisdiver.otisarena;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import me.otisdiver.otisarena.event.JoinQuit;
import me.otisdiver.otisarena.event.GameDeath;
import me.otisdiver.otisarena.event.LobbyGuard;
import me.otisdiver.otisarena.event.StartingCanceller;
import me.otisdiver.otisarena.event.WorldGuard;
import me.otisdiver.otisarena.game.Game;
public class OtisArena extends JavaPlugin {
private Game game;
private JoinQuit joinQuit;
public void onEnable() {
// instantiate the game class
game = new Game(this);
// load the config
ConfigUtils.initiate(this);
// register event listeners
joinQuit = new JoinQuit(this);
new StartingCanceller(this);
new GameDeath(this);
new LobbyGuard(this);
new WorldGuard(this);
}
public void onDisable() {
// unload world
Bukkit.unloadWorld(game.getActiveWorld().getName(), false);
}
public Game getGame() {
return game;
}
}
| clean up JoinQuit registration
no longer need to save the listener in OtisArena, see 35a130756ccf1b91dce15ec673bf2493cc4f9f3a
| src/main/java/me/otisdiver/otisarena/OtisArena.java | clean up JoinQuit registration no longer need to save the listener in OtisArena, see 35a130756ccf1b91dce15ec673bf2493cc4f9f3a | <ide><path>rc/main/java/me/otisdiver/otisarena/OtisArena.java
<ide> public class OtisArena extends JavaPlugin {
<ide>
<ide> private Game game;
<del> private JoinQuit joinQuit;
<ide>
<ide> public void onEnable() {
<ide>
<ide> ConfigUtils.initiate(this);
<ide>
<ide> // register event listeners
<del> joinQuit = new JoinQuit(this);
<add> new JoinQuit(this);
<ide> new StartingCanceller(this);
<ide> new GameDeath(this);
<ide> new LobbyGuard(this); |
|
JavaScript | mit | d4711bd19f4757bd3f1ac88455b1d1e998eb3bb6 | 0 | iMarck/radiotime-tools,iMarck/radiotime-tools,tunein/radiotime-tools,tunein/radiotime-tools | /**
* radiotime.js -- API, helper functions and objects
*
* @author alex
* @author Jeremy Dunck <[email protected]>
*
*
*/
var RadioTime = {
_baseUrls: {
"stable": "opml.radiotime.com/",
"beta": "dev.radiotime.com/opml/",
"dev": "localhost:55084/opml/"
},
init: function(partnerId, containerId, path, opts) {
this._partnerId = partnerId;
this._container = document.getElementById(containerId);
this._path = path;
this._serial = this.cookie.read("radiotime_serial");
if (!this._serial) {
this._serial = this.makeId();
this.cookie.save("radiotime_serial", this._serial, 365*10);
}
opts = opts || {};
this._env = (opts.env && this._baseUrls[opts.env]) ? opts.env: "stable";
this._baseUrl = this._baseUrls[this._env];
this._verbose = opts.verbose;
this._useAMPM = opts.useAMPM !== undefined ? opts.useAMPM: true;
this._enableEvents = opts.enableEvents !== undefined ? opts.enableEvents: true;
this.latlon = opts.latlon;
this._exactLocation = opts.exactLocation;
if (opts.player) {
this.addPlayer(opts.player);
}
this._initKeys();
this._initEventHandlers();
var supportedPlayer = false;
if (!opts.noPlayer) {
for (var i = 0; i< RadioTime._players.length; i++) {
if (supportedPlayer = RadioTime._players[i].isSupported()) {
RadioTime.merge(RadioTime.player, RadioTime._players[i].implementation);
break;
}
};
}
if (supportedPlayer) {
this.player.init(this._container);
this.formats = RadioTime.player.formats;
RadioTime.debug("Using player: " + this.player.playerName);
} else {
if (!opts.noPlayer) {
alert("Unable to find a supported audio player");
RadioTime.formats = opts.formats ? opts.formats : ["mp3","wma"];
} else {
RadioTime.formats = ["mp3", "wma"];
}
};
this.history = this._histories[opts['history'] || 'internal'];
this.history._init(opts['onHistoryChange']);
// We don't need accurate time immediately so postpone it a bit
// to give room for UI to load
setTimeout(function(){
RadioTime._syncTime();
}, 3*1000);
},
_addScript: function(url, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('src', url);
script.onload = function() {
head.removeChild(script);
onload();
}
head.appendChild(script);
},
/* Platform key contants
* need to define these so that it won't break while testing in a browser
* also it provides a nice way to emulate
*/
_keys: { //TODO (SDK): map CE keys into private space rather than browser keys into global space.
VK_0: 48,
VK_1: 49,
VK_2: 50,
VK_3: 51,
VK_4: 52,
VK_5: 53,
VK_6: 54,
VK_7: 55,
VK_8: 56,
VK_9: 57,
VK_ENTER: 13,
VK_UP: 38,
VK_DOWN: 40,
VK_LEFT: 37,
VK_RIGHT: 39,
VK_BACK: 27,
VK_BACK_SPACE: 8,
VK_PLAY: 190, // "."
VK_STOP: 188, // ","
VK_PAUSE: 191 // "/"
},
_initKeys: function() {
for (var key in this._keys) {
if (typeof window[key] == "undefined") {
window[key] = this._keys[key];
}
}
},
_initEventHandlers: function() {
RadioTime.event.subscribe("playstateChanged", function(state) {
RadioTime.player.currentState = state;
switch (RadioTime.player.currentState) {
case "playing":
case "buffering":
case "connecting":
RadioTime.player.isBusy = true;
break;
default:
RadioTime.player.isBusy = false;
break;
}
});
},
_syncTime: function(){
var now = new Date();
this.timeCorrection = 0;
this.gmtOffset = -now.getTimezoneOffset();
var _this = this;
RadioTime.API.getTime(function(data){
RadioTime.debug("Got accurate time");
data = data[0];
RadioTime.debug(data);
_this.gmtOffset = parseInt(data.detected_offset);
_this.tzName = data.detected_tz;
_this.timeCorrection = parseInt(data.utc_time)*1000 - (+new Date());
RadioTime.debug("adjusted gmtOffset = " + _this.gmtOffset + " minutes");
RadioTime.debug("timeCorrection = " + _this.timeCorrection + " milliseconds");
RadioTime.debug("Time sync took " + ((+new Date()) - (+now)) + " ms");
});
},
player: {
startPlaylist: function(playlist) {
if (!playlist || !playlist.length)
return;
this._playlist = playlist;
this._currentItem = 0;
this.play();
},
next: function() {
if (!this._playlist || !this._playlist.length)
return;
if (this._currentItem < this._playlist.length - 1) {
this._currentItem++;
this.play();
} else {
RadioTime.event.raise("playlistEnded");
}
},
play: function(url) {
if (url) {
this._playlist = [{"url":url}];
this._currentItem = 0;
}
var newUrl = "";
if (this._playlist) {
newUrl = this._playlist[this._currentItem].url;
}
// Don't stop unless the URL is different
if (newUrl != this._url) {
this.stop();
this._url = newUrl;
}
if (!this._url) {
return;
}
this._play(this._url);
},
isSupported: function() {
return !!this._play;
}
},
addPlayer: function(player) {
this._players.unshift([function() { return true; }, player]);
},
_players: [
{
isSupported: function() {
return navigator.userAgent.match(/CE-HTML/);
},
implementation: {
init: function(container) {
this.playerName = "ce";
this.formats = ["mp3"];
var d = document.createElement("div");
this._id = RadioTime.makeId();
d.innerHTML = '<object id="' + this._id + '" type="audio/mpeg"></object>';
container.appendChild(d);
this._player = RadioTime.$(this._id);
},
_play: function(url){
if (!this._player || !this._player.play)
return;
this._player.data = this._url;
this._player.play(1);
var _this = this;
this._player.onPlayStateChange = function() {
if (5 == _this._player.playState) {
RadioTime.player.next();
}
RadioTime.event.raise("playstateChanged", RadioTime.player.states[_this._player.playState]);
}
},
stop: function() {
if (!this._player || !this._player.stop)
return;
this._player.stop();
},
pause: function() {
if (!this._player || !this._player.play)
return;
this._player.play(); // this actually means 'pause' on CE!
},
states: {
5: "finished",
0: "stopped",
6: "error",
1: "playing",
2: "paused",
3: "connecting",
4: "buffering"
}
}
},
{
isSupported: function() { return window.songbird; },
implementation: { //FIXME: need to integrate more to do eventing based on player transitions.
// var listener = { observe: function(subject, topic, data) {...}}; songbird.addListener("faceplate.playing", listener)
init: function () {
this.playerName = 'songbird';
this.formats = ["mp3"];
songbird.setSiteScope("", "");
this.library = songbird.siteLibrary;
},
_play: function (url) {
//FIXME: it'd be nice to resume from pause (because it's faster),
// but that would mean juggling state w/ the host player (it could be paused on a local Library song)
//FIXME: switch to createMediaListFromURL? :-/
songbird.playURL(url);
//FIXME: need mediacore listener to sync w/ real state:
RadioTime.event.raise("playstateChanged", RadioTime.player.states[1]);
},
stop: function() {
songbird.stop();
RadioTime.event.raise("playstateChanged", RadioTime.player.states[0]);
},
pause: function() {
songbird.pause();
RadioTime.event.raise("playstateChanged", RadioTime.player.states[2]);
},
states: {
0: "stopped",
1: "playing",
2: "paused"
}
}
},
{
isSupported: function() {
var f = "-", n = navigator;
if (n.plugins && n.plugins.length) {
for (var ii=0; ii<n.plugins.length; ii++) {
if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
f = n.plugins[ii].description.split('Shockwave Flash ')[1];
break;
}
}
} else if (window.ActiveXObject) {
for (var ii=10; ii>=2; ii--) {
try {
var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + ii + "');");
if (fl) {
f = ii + '.0';
break;
}
}
catch(e) {}
}
}
if (f.split(".")[0]) {
f = f.split(".")[0];
}
return (f > 8);
},
implementation:
{
init: function(container) {
this.playerName = 'flash';
this.formats = ["mp3", "flash"];
var d = document.createElement("div");
container.appendChild(d);
d.style.position = "absolute";
this._id = RadioTime.makeId();
var flashvars = '"autostart=true&objectid=' + this._id + '"';
if (/MSIE/.test(navigator.userAgent)) { // IE detection ~[-1]
d.innerHTML = '<object id="' + this._id + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="1" height="1"><param name="allowScriptAccess" value="always" /><param name="movie" value="' + RadioTime._path + 'swf/mplayer.swf?' + this._id + '" /><param name="flashvars" value=' + flashvars + '/></object>';
} else {
d.innerHTML = '<embed id="' + this._id + '" type="application/x-shockwave-flash" width="1" height="1" src="' + RadioTime._path + 'swf/mplayer.swf?' + this._id + '" allowscriptaccess="always" flashvars=' + flashvars + '/>';
}
container.innerHTML;
this._player = d.firstChild;
//this._player = RadioTime.$(this._id);
var _this = this;
RadioTime.event.subscribe("flashEvent", function(params) {
if (_this._id != params.objectid)
return;
switch (params.command) {
case "status":
if (5 == parseInt(params.arg)) {
RadioTime.debug("player next");
RadioTime.player.next();
}
RadioTime.debug("flashEvent status", params.arg);
RadioTime.event.raise("playstateChanged", RadioTime.player.states[params.arg]);
break;
case "progress":
case "position":
case "nowplaying":
break;
case "ready":
RadioTime.debug("flash object is ready");
break;
}
if (params.command != "position")
RadioTime.debug(params);
});
},
_play: function(url) {
if (!this._player || !this._player.playDirectUrl)
return;
this._player.playDirectUrl(url);
},
stop: function() {
if (!this._player || !this._player.doStop)
return;
this._player.doStop();
},
pause: function() {
if (!this._player || !this._player.doPause)
return;
this._player.doPause();
},
states: {
5: "finished",
0: "unknown",
1: "stopped",
2: "connecting",
3: "playing",
4: "error"
}
}
},{
isSupported: function() {
// iPad-only for now
return /iPad/i.test(navigator.userAgent);
},
implementation: {
init: function(container){
this.playerName = "html5";
this.formats = ["mp3", "aac"];
var d = new Audio();
this._id = RadioTime.makeId();
d.id = this._id;
container.appendChild(d);
this._player = RadioTime.$(this._id);
var _this = this;
/*
* <audio> event handlers
*/
this._player.addEventListener('error', function(){
_this._stateChanged('error');
}, true);
this._player.addEventListener('playing', function(){
_this._stateChanged('playing');
}, true);
this._player.addEventListener('pause', function(){
_this._stateChanged('pause');
}, true);
this._player.addEventListener('ended', function(){
_this._stateChanged('ended');
RadioTime.player.next();
}, true);
this._player.addEventListener('abort', function(){
_this._stateChanged('abort');
}, true);
this._player.addEventListener('loadstart', function(){
_this._stateChanged('loadstart');
}, true);
this._player.addEventListener('seeking', function(){
_this._stateChanged('seeking');
}, true);
this._player.addEventListener('waiting', function(){
_this._stateChanged('waiting');
}, true);
this._player.addEventListener('suspend', function(){
_this._stateChanged('suspend');
}, true);
this._player.addEventListener('stalled', function(){
_this._stateChanged('stalled');
}, true);
},
_stateChanged: function(newstate){
var state = "stopped";
switch (newstate) {
case "pause":
state = "paused";
break;
case "stalled":
case "suspend":
case "ended":
case "stopped":
state = "stopped";
break;
case "playing":
state = "playing";
break;
case "loadstart":
case "waiting":
case "seeking":
state = "connecting";
break;
case "error":
state = "error";
break;
}
RadioTime.event.raise("playstateChanged", RadioTime.player.states[state]);
},
_play: function(url){
if (this._player.src != url) {
this._player.src = this._url;
this._player.load();
}
this._player.play();
},
stop: function(){
this._player.pause();
},
pause: function(){
this._player.pause();
},
states: {
"finished": "finished",
"stopped": "stopped",
"error": "error",
"playing": "playing",
"paused": "paused",
"connecting": "connecting"
}
}
}
],
schedule: {
_tickInterval: 1, // seconds between Now playing progress updates
_tickReg: null, //non-null if progress is running
_fetchInterval: 10, // seconds between Next on updates
_fetchReg: null, //non-null if fetch is running
schedule: null,
nowPlayingIndex: -1,
guide_id: null,
init: function(guide_id) {
var _this = this;
this.stopUpdates();
this._fetch(guide_id);
},
_fetch: function(guide_id) {
RadioTime.debug("fetch with " + guide_id);
if (!guide_id) return;
if (this.lastUpdate && this.lastUpdate.getHours && this.lastUpdate.getHours() == RadioTime.now().getHours()){
this._available(this.schedule);
return;
}
var _this = this;
RadioTime.debug("RadioTime.API.getStationSchedule with " + guide_id);
RadioTime.API.getStationSchedule(function(data){
_this.guide_id = guide_id;
_this._available(data);
}, function() { RadioTime.debug("Failed to get schedule") }, guide_id);
this.lastUpdate = RadioTime.now();
},
/*
* Pre-process schedule
*/
_available: function(data) {
if (!data) return;
this.schedule = data;
var now = RadioTime.now();
var _this = this;
var oldNowPlayingIndex = (typeof this.nowPlayingIndex != "undefined") ? this.nowPlayingIndex : -2;
this.nowPlayingIndex = -1;
for (var i = 0; i < data.length; i++) {
// Skip the past
if (data[i].end < now.getTime()) {
continue;
}
// This is what playing now
if (data[i].start < now.getTime() && data[i].end > now.getTime()) {
this.nowPlayingIndex = i;
data[i].is_playing = true;
if (this._tickReg) {
clearInterval(this._tickReg);
}
this._tickReg = setInterval(function(){
_this._tick();
}, this._tickInterval*1000);
continue;
} else {
data[i].is_playing = false;
}
}
if (this._fetchReg) {
clearTimeout(this._fetchReg);
}
if (this.nowPlayingIndex < 0) { // Nothing is playing
this._fetchReg = setTimeout(function(){
_this._fetch(_this.guide_id);
}, this._fetchInterval*1000);
}
if (this.nowPlayingIndex != oldNowPlayingIndex) {
RadioTime.event.raise("schedule", data);
}
},
_tick: function() {
if (this.nowPlayingIndex < 0 || !this.schedule || !this.schedule[this.nowPlayingIndex]) {
return;
}
RadioTime.event.raise("scheduleProgress", {
start: this.schedule[this.nowPlayingIndex].start,
end: this.schedule[this.nowPlayingIndex].end
});
if (this.schedule[this.nowPlayingIndex].end < RadioTime.now().getTime()) {
this._available(this.schedule);
};
},
stopUpdates: function() {
if (this._tickReg) {
clearInterval(this._tickReg);
}
if (this._fetchReg) {
clearTimeout(this._fetchReg);
}
this.lastUpdate = null;
this.nowPlayingIndex = null;
this.guide_id = null;
}
},
logoSizes: {"square": "q", "small": "s", "normal": ""},
logoFormats: {"png":"png","gif":"gif"},
getLogoUrl: function(guide_id, logoSize, logoFormat) {
var logoSizeCode = RadioTime.logoSizes[logoSize] || "";
var logoFormat = RadioTime.logoFormats[logoFormat] || "png";
return "http://radiotime-logos.s3.amazonaws.com/" + guide_id + logoSizeCode + "." + logoFormat;
},
_formatReq: function(url, needAuth, data) {
// Prepare the URL
data = data || "";
// Avoid formatting it twice
if (url.url) {
return url;
}
if (url.indexOf("http") < 0) { // default request path
url = (needAuth ? "https://" : "http://") + RadioTime._baseUrl + url;
}
url += (url.indexOf("?")!=-1 ? "&" : "?");
if (url.indexOf("partnerId") < 0 && data.indexOf("partnerId") < 0) {
url += "partnerId=" + RadioTime._partnerId + "&";
}
if (url.indexOf("username") < 0 && url.indexOf("serial") < 0 && data.indexOf("serial") < 0) {
url += "serial=" + RadioTime._serial + "&";
}
if (!needAuth && RadioTime.formats && url.indexOf("formats") < 0 && data.indexOf("formats") < 0) {
url += "formats=" + RadioTime.formats.join(",") + "&";
}
if (RadioTime.latlon && url.indexOf("latlon") < 0 && data.indexOf("latlon") < 0) {
url += "latlon=" + RadioTime.latlon + "&";
if (RadioTime._exactLocation && url.indexOf("exact") < 0 && data.indexOf("exact") < 0) {
url += "exact=1&"
}
}
if (!needAuth && RadioTime.locale && url.indexOf("locale") < 0 && data.indexOf("locale") < 0) {
url += "locale=" + RadioTime.locale + "&";
}
if (-1 == url.indexOf("render=json")) {
url += "render=json&";
}
return {"url": url, "data": data};
},
loadJSON: function(url, onsuccess, onfailure) {
url = RadioTime._formatReq(url);
RadioTime.debug("API request: " + url.url);
RadioTime._loader.sendRequest(url, function(data) {
var status = (data.head && data.head.status) ? data.head.status : "missing";
if (status == "200") { // Status is not returned for Register.aspx call
if (data && onsuccess) {
onsuccess.call(this, data.body, data.head);
}
} else {
if (onfailure) onfailure.call(null, data.head);
}
RadioTime.event.raise("loaded");
}, function() {
if (onfailure) onfailure.call(null);
RadioTime.event.raise("failed", url);
});
},
_getIdType: function(guideId) {
if (!guideId) return "unknown";
switch (guideId.charAt(0)) {
case "p":
return "program";
case "s":
return "station";
case "g":
return "group";
case "t":
return "topic";
case "c":
return "category";
case "r":
return "region";
case "f":
return "podcast_category"; //???
case "a":
return "affiliate";
case "e":
return "stream";
default:
return "unknown";
}
},
now: function() {
return (
new Date(
(+new Date()) +
this.timeCorrection +
(this.gmtOffset + (new Date()).getTimezoneOffset())*60*1000
)
);
},
_dateToYYYYMMDD: function(date) {
var out = '';
out += date.getFullYear();
var mon = date.getMonth() + 1;
out += (mon < 10) ? "0" + mon : mon;
var dat = date.getDate();
out += (dat < 10) ? "0" + dat : dat;
return out;
},
formatTime: function(time) {
if (typeof time != "object") {
var ts = time;
time = RadioTime.now();
time.setTime(ts);
}
var out = '';
if (RadioTime._useAMPM) {
var hours = time.getHours();
var suffix = "am";
switch (true) {
case (hours == 0) :
hours = 12;
suffix = "am";
break;
case (hours == 12):
suffix = "pm";
break;
case (hours > 12):
suffix = "pm";
hours -= 12
break
default:
break;
}
out = (hours + 0.01*time.getMinutes()).toFixed(2).replace(".", ":") + suffix;
} else {
out = (time.getHours() + 0.01*time.getMinutes()).toFixed(2).replace(".", ":");
}
return out.replace(/^(\d):/, '0$1:');
},
_dateFromServicesString: function(dateString) {
var out = new Date(dateString.replace("T", " ").replace(/-/g, "/"));
out.setTime(out.getTime());
return out;
},
_calculateEndTime: function(startTime, duration /*seconds*/) {
var endTime = RadioTime.now();
if (isNaN(startTime)) startTime = startTime.getTime();
endTime.setTime(startTime + duration*1000);
return endTime;
},
_histories: { //TODO (SDK) switch to hash-tag history system to allow browser back/forward to work.
"internal": {
_history: [],
_equals: function(o1, o2) {
return (o1.URL == o2.URL);
},
_init: function(onHistoryChange) {
this.onHistoryChange = onHistoryChange;
},
back: function() {
if (this._history.length > 0) {
this._history.pop();
this.onHistoryChange(this.last());
return true;
} else {
return false;
}
},
add: function(object){
RadioTime.debug("history add");
RadioTime.debug(object);
//if (!this.history.length || !this._equals(this.last(), object)) {
object.restorePoint = false;
this._history.push(object);
//}
},
last: function() {
RadioTime.debug("history last");
return (this._history.length > 0) ? this._history[this._history.length - 1] : null;
},
reset: function() {
RadioTime.debug("history clear");
while(this._history.length > 2) { //FIXME: CE assuming first = home is bad for general SDK apps.
RadioTime.debug("... back");
this._history.pop();
}
},
createRestorePoint: function() {
if (this.last()) {
this.last().restorePoint = true;
}
},
restore: function() {
var hasRestorePoint = false;
for (var i = this._history.length - 1; i >=0; i--) {
if (this._history[i].restorePoint){
//this.history[i].restorePoint = false;
this._history = this._history.slice(0, i + 1);
break;
}
}
}
},
'hash': { //FIXME: assuming (as RSH does) that the hash is ours to use is bad for multi-widget pages.
_seq: 0, //used to make a unique hash for browser-based history.
_restores: {},
_init: function(onHistoryChange) {
dhtmlHistory.initialize();
dhtmlHistory.addListener(function(newLocation, historyData) {
RadioTime.history._seq = RadioTime.history._parseSequence(newLocation) + 1;
if (onHistoryChange) {
onHistoryChange(historyData);
}
})
},
_makeHash: function(seq) {
return "history" + seq;
},
_parseSequence: function(hash) {
if (-1 == hash.indexOf("history")) {
return 0;
} else {
return parseInt(hash.replace("history",""));
}
},
back: function() {
window.history.back();
},
add: function(obj) {
var hash = this._makeHash(this._seq++);
dhtmlHistory.add(hash, obj);
},
last: function() {
var key = dhtmlHistory.getCurrentLocation();
if (historyStorage.hasKey(key)) {
return historyStorage.get(dhtmlHistory.getCurrentLocation());
} else {
return null;
}
},
reset: function() {
//this._seq = 0;
//this.restores = {};
//window.location.hash = "";
}, //no-op because browser history can handle it (and RSH doesn't have an easy way to clear).
createRestorePoint: function() {
if (this._seq > 0) {
this._restores[this._seq] = true;
}
},
restore: function() {
var hasRestorePoint = false;
for (var i = his._seq; i >=0; i--) {
if (this._restores[i]){
this._seq = i;
window.location.hash = "#" + this._seq;
}
}
}
}
},
_isArray: function(v) {
return v && typeof v === 'object' && typeof v.length === 'number' &&
!(v.propertyIsEnumerable('length'));
},
_isString: function(it) {
return (typeof it == "string" || it instanceof String);
},
_hitch: function(scope, method) { //From Dojo Toolkit, returns a function which executes with "this" bound to scope.
if(_isString(method)){ //more info on why it's needed: http://www.quirksmode.org/js/this.html
scope = scope || window;
return function(){ return scope[method].apply(scope, arguments || []); };
}
return function(){ return method.apply(scope, arguments || []); };
},
getTuneUrl: function(guideId) {
return this._formatReq("Tune.ashx?id=" + guideId).url;
},
API: {
getCategory: function(success, failure, category) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Browse.ashx?c=" + category, success, failure);
},
getRootMenu: function(success, failure) {
RadioTime.event.raise("loading", 'status_loading_menu');
RadioTime.loadJSON("Browse.ashx", success, failure);
},
getStationSchedule: function(success, failure, id){ //TODO (SDK) - add optional time range.
var startDate = RadioTime.now();
var stopDate = RadioTime.now();
stopDate.setTime(startDate.getTime() + 1000 * 60 * 60 * 24);
startDate.setTime(startDate.getTime() - 1000 * 60 * 60 * 24);
//FIXME: seems we should either autodetect (as here) or use offset (as RT getTime above), but not both.
var url = "Browse.ashx?c=schedule&id=" + id + "&start=" + RadioTime._dateToYYYYMMDD(startDate) +
"&stop=" + RadioTime._dateToYYYYMMDD(stopDate) + "&autodetect=true";// + "&offset=" + RadioTime.gmtOffset;
RadioTime.event.raise("loading", 'status_loading_schedule');
RadioTime.loadJSON(url, function(data) {
var now = RadioTime.now().getTime();
// Pre-process the data
for (var i = 0; i < data.length; i++) {
data[i].start = RadioTime._dateFromServicesString(data[i].start).getTime();
data[i].end = RadioTime._calculateEndTime(data[i].start, data[i].duration).getTime();
data[i].is_playing = (data[i].start < now) && (data[i].end > now);
var str = RadioTime.formatTime(data[i].start);
data[i].timeSpanString = str;
data[i].index = i;
data[i].oType = RadioTime._getIdType(data[i].guide_id);
}
success.call(this, data);
}, failure);
},
getProgramListeningOptions: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Tune.ashx?c=sbrowse&flatten=true&id=" + id, success, failure);
},
describe: function(success, failure, id){
RadioTime.event.raise("loading", 'status_finding_stations');
RadioTime.loadJSON("Describe.ashx?id=" + id, success, failure);
},
tune: function(success, failure, guideId) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON(RadioTime.getTuneUrl(guideId), success, failure);
},
getOptions: function(success, failure, id){
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Options.ashx?id=" + id, success, failure);
},
getRelated: function(success, failure, id){
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Browse.ashx?id=" + id, success, failure);
},
addPreset: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_adding_preset');
var url = RadioTime._formatReq("Preset.ashx?c=add&id=" + id, true);
RadioTime.loadJSON(url, success, failure)
},
removePreset: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_removing_preset');
var url = RadioTime._formatReq("Preset.ashx?c=remove&id=" + id, true);
RadioTime.loadJSON(url, success, failure)
},
search: function(success, failure, query, filter) {
RadioTime.event.raise("loading", 'status_searching');
var url = RadioTime._formatReq("Search.ashx?query=" + query + "&filter=" + filter);
RadioTime.loadJSON(url, success, failure)
},
getAccountStatus: function(success, failure) {
RadioTime.event.raise("loading", 'status_checking_account');
var url = RadioTime._formatReq("Account.ashx?c=query", true);
RadioTime.loadJSON(url, function(data){
var out = {
"hasAccount": true,
"text": data[0].text
}
success.call(this, out);
}, function(){
var u = RadioTime._formatReq("Account.ashx?c=claim", true);
RadioTime.loadJSON(u, function(data){
var out = {
"hasAccount": false,
"text": data[0].text
}
success.call(this, out);
}, failure);
});
},
getLocalStrings: function(success, failure) {
RadioTime.event.raise("loading", 'status_loading');
var url = RadioTime._formatReq("Config.ashx?c=contentQuery");
RadioTime.loadJSON(url, function(data) {
RadioTime._applyLocalStrings(data);
success(data);
}, failure);
},
getTime: function(success, failure) {
RadioTime.event.raise("loading", 'status_sync_time');
var url = RadioTime._formatReq("Config.ashx?c=time");
RadioTime.loadJSON(url, success, failure)
}
},
response: {
audio: function (body) {
var out = [];
RadioTime._walk(body,
function(elem) {
if (elem.element == "outline" && elem.type == "audio") {
out.push(elem);
}
}
);
return out;
},
flatten: function (data, copyKey) {
var out = [];
for (var i = 0; i < data.length; i++ ) {
out.push(data[i]);
if (data[i].children) {
if (data[i].key && copyKey) {
for (var j in data[i].children) {
data[i].children[j].key = data[i].key;
}
}
out = out.concat(this.flatten(data[i].children, copyKey));
}
}
return out;
},
station: function(body) {
var out = [];
var inStationsDepth = -1;
RadioTime._walk(body,
function(elem, depth) {
if (inStationsDepth > depth) {
inStationsDepth = -1;
return
};
if (elem.key == 'stations') {
inStationsDepth = depth + 1;
return;
}
if (inStationsDepth > -1) {
out.push(elem);
} else {
if (RadioTime._getIdType(elem.guide_id) == "station") {
out.push(elem);
}
}
}
);
return out;
}
},
_walk: function(tree, handler, depth) {
depth = depth || 0;
if (RadioTime._isArray(tree)) {
for (var i=0; i < tree.length; i++) {
RadioTime._walk(tree[i], handler, depth);
}
} else {
handler(tree, depth);
if (tree.children) {
RadioTime._walk(tree.children, handler, depth + 1);
}
}
},
_applyLocalStrings: function(locale) {
var out = {};
for (var i in locale) {
out[locale[i].key] = locale[i].value;
}
RadioTime.merge(out, RadioTime.localStrings);
RadioTime.localStrings = out;
RadioTime.event.raise("localStrings");
},
_loader: {
_requestTimeout: 30, // in seconds
requests: {},
sendRequest: function(req, success, failure, retries) {
if (typeof req != 'number') { // this is a new request
var reqId = RadioTime.makeId();
this.requests[reqId] = {
_req: req,
_requestCompleted: false,
_callback: success != undefined ? success : null,
_failure: failure != undefined ? failure : null,
_retries: retries != undefined ? retries : 0,
_reqUrl: (req.url.indexOf("callback=") < 0) ? req.url + "callback=RadioTime._loader.requests[" + reqId + "].init" : req.url,
init: function(data) {
this._requestCompleted = true;
if (this._callback) {
this._callback.call(this, data);
}
},
fail: function() {
if (this._failure) {
this._failure.call(this);
}
}
};
} else {
var reqId = req;
if (this.requests[reqId] == undefined)
return;
// OK
if (this.requests[reqId]._requestCompleted) {
this.clearRequest(reqId);
return;
}
// No retries left?
if (this.requests[reqId]._retries <= 0) {
this.onerror(this.requests[reqId]);
this.clearRequest(reqId);
return;
}
this.requests[reqId]._retries--;
}
if (RadioTime.$(reqId)) {
RadioTime.$(reqId).parentNode.removeChild(RadioTime.$(reqId));
}
var s;
var _this = this;
if (this.requests[reqId]._callback) {
s = document.createElement("script");
s.onload = function() {
}
} else { // use iframe if we don't care about result
s = document.createElement("iframe");
s.style.visibility = "hidden";
s.style.width = "1px";
s.style.height = "1px";
s.onload = function() {
_this.clearRequest(this.id);
}
}
s.id = reqId;
s.src = this.requests[reqId]._reqUrl;
RadioTime._container.appendChild(s);
setTimeout(function() {
_this.sendRequest(reqId);
}, this._requestTimeout*1000);
},
clearRequest: function(reqId) {
if (RadioTime.$(reqId)) {
RadioTime.$(reqId).parentNode.removeChild(RadioTime.$(reqId));
delete this.requests[reqId];
} else {
if (this.requests[reqId] && !this.requests[reqId]._requestCompleted) {
var _this = this;
this.requests[reqId].init = function(data){
RadioTime.debug("Late request arrived: " + reqId);
_this.clearRequest(reqId);
}
}
}
},
onerror: function(req) {
req.fail();
}
},
event: {
_handlers: [],
_hid: 0,
subscribe: function (eventName, handler, forObj) {
if (!this._handlers[eventName]) {
this._handlers[eventName] = [];
}
var h = {};
h.func = handler;
h.forObj = forObj; // if obj is "undefined" then treat handler as default
h.id = this._hid++;
this._handlers[eventName].push(h);
return h.id;
},
unsubscribe: function(hid) {
for (var event_ in this._handlers) {
for (var handler in this._handlers[event_]) {
if (this._handlers[event_][handler].id == hid) {
this._handlers[event_].splice(handler, 1);
return true;
}
}
}
return false;
},
raise: function(eventName, params, toObj) {
if (!RadioTime._enableEvents) return true;
if (!this._handlers[eventName]) {
//RadioTime.debug("No handlers for " + eventName, "warning")
return true;
}
var eh = this._handlers[eventName];
for (handler in eh) {
if (eh[handler].func && (eh[handler].forObj == toObj || eh[handler].forObj == undefined)) {
eh[handler].func.call(eh[handler].forObj, params);
}
}
}
},
$: function(name) {
var el = document.getElementById(name);
if (!el) {
RadioTime.debug('Element "',name, '" is not found');
}
return el;
},
/*
* Get localized string
*/
L: function(token) {
return this.localStrings[token] || token;
},
localStrings: {},
debug: function(){
if (!RadioTime._verbose) return;
if (arguments.length == 1) {
var txt = arguments[0];
} else {
var txt = Array.prototype.slice.call(arguments).join(" ");
}
if (window.console && console.debug) {
console.debug.apply(console, arguments);
} else {
// Can't use RadioTime.$ here because it would cause infinite recruision
// and stack overflow due to the debug() call in RadioTime.$
if (document.getElementById("radiotime_log")) {
document.getElementById("radiotime_log").innerHTML += txt + ", ";
}
}
},
makeId: function() {
return 1*(Math.random().toString().replace('.', ''));
},
_trim: function(s) {
return s.match(/^\s*(.*?)\s*$/)[1];
},
merge: function(target, source, useSuper){
if (useSuper) {
target.SUPER = {};
target.callSuper = function() {
var function_name = arguments[0];
[].unshift.call(arguments, this);
if (typeof this.SUPER[function_name] != "undefined") {
return this.SUPER[function_name].apply(this, arguments);
} else {
return false;
}
}
}
for (var i in source){
if (!target[i]) {
target[i] = source[i];
} else if (useSuper) {
target.SUPER[i] = source[i];
}
}
},
cookie: {
save: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
read: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
clear: function (name) {
this.save(name,"",-1);
}
},
/**
* This function is called from Flash
* @param {Object} command
* @param {Object} arg
* @param {Object} objectid
*/
getUpdate: function(command, arg, objectid) {
var params ={
"command": command,
"arg": arg,
"objectid": objectid
}
RadioTime.event.raise("flashEvent", params);
}
}
| clients/js/src/js/radiotime.js | /**
* radiotime.js -- API, helper functions and objects
*
* @author alex
* @author Jeremy Dunck <[email protected]>
*
*
*/
var RadioTime = {
_baseUrls: {
"stable": "opml.radiotime.com/",
"beta": "dev.radiotime.com/opml/",
"dev": "localhost:55084/opml/"
},
init: function(partnerId, containerId, path, opts) {
this._partnerId = partnerId;
this._container = document.getElementById(containerId);
this._path = path;
this._serial = this.cookie.read("radiotime_serial");
if (!this._serial) {
this._serial = this.makeId();
this.cookie.save("radiotime_serial", this._serial, 365*10);
}
opts = opts || {};
this._env = (opts.env && this._baseUrls[opts.env]) ? opts.env: "stable";
this._baseUrl = this._baseUrls[this._env];
this._verbose = opts.verbose;
this._useAMPM = opts.useAMPM !== undefined ? opts.useAMPM: true;
this._enableEvents = opts.enableEvents !== undefined ? opts.enableEvents: true;
this.latlon = opts.latlon;
this._exactLocation = opts.exactLocation;
if (opts.player) {
this.addPlayer(opts.player);
}
this._initKeys();
this._initEventHandlers();
var supportedPlayer = false;
if (!opts.noPlayer) {
for (var i = 0; i< RadioTime._players.length; i++) {
if (supportedPlayer = RadioTime._players[i].isSupported()) {
RadioTime.merge(RadioTime.player, RadioTime._players[i].implementation);
break;
}
};
}
if (supportedPlayer) {
this.player.init(this._container);
this.formats = RadioTime.player.formats;
RadioTime.debug("Using player: " + this.player.playerName);
} else {
if (!opts.noPlayer) {
alert("Unable to find a supported audio player");
RadioTime.formats = opts.formats ? opts.formats : ["mp3","wma"];
} else {
RadioTime.formats = ["mp3", "wma"];
}
};
this.history = this._histories[opts['history'] || 'internal'];
this.history._init(opts['onHistoryChange']);
// We don't need accurate time immediately so postpone it a bit
// to give room for UI to load
setTimeout(function(){
RadioTime._syncTime();
}, 3*1000);
},
_addScript: function(url, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('src', url);
script.onload = function() {
head.removeChild(script);
onload();
}
head.appendChild(script);
},
/* Platform key contants
* need to define these so that it won't break while testing in a browser
* also it provides a nice way to emulate
*/
_keys: { //TODO (SDK): map CE keys into private space rather than browser keys into global space.
VK_0: 48,
VK_1: 49,
VK_2: 50,
VK_3: 51,
VK_4: 52,
VK_5: 53,
VK_6: 54,
VK_7: 55,
VK_8: 56,
VK_9: 57,
VK_ENTER: 13,
VK_UP: 38,
VK_DOWN: 40,
VK_LEFT: 37,
VK_RIGHT: 39,
VK_BACK: 27,
VK_BACK_SPACE: 8,
VK_PLAY: 190, // "."
VK_STOP: 188, // ","
VK_PAUSE: 191 // "/"
},
_initKeys: function() {
for (var key in this._keys) {
if (typeof window[key] == "undefined") {
window[key] = this._keys[key];
}
}
},
_initEventHandlers: function() {
RadioTime.event.subscribe("playstateChanged", function(state) {
RadioTime.player.currentState = state;
switch (RadioTime.player.currentState) {
case "playing":
case "buffering":
case "connecting":
RadioTime.player.isBusy = true;
break;
default:
RadioTime.player.isBusy = false;
break;
}
});
},
_syncTime: function(){
var now = new Date();
this.timeCorrection = 0;
this.gmtOffset = -now.getTimezoneOffset();
var _this = this;
RadioTime.API.getTime(function(data){
RadioTime.debug("Got accurate time");
data = data[0];
RadioTime.debug(data);
_this.gmtOffset = parseInt(data.detected_offset);
_this.tzName = data.detected_tz;
_this.timeCorrection = parseInt(data.utc_time)*1000 - (+new Date());
RadioTime.debug("adjusted gmtOffset = " + _this.gmtOffset + " minutes");
RadioTime.debug("timeCorrection = " + _this.timeCorrection + " milliseconds");
RadioTime.debug("Time sync took " + ((+new Date()) - (+now)) + " ms");
});
},
player: {
startPlaylist: function(playlist) {
if (!playlist || !playlist.length)
return;
this._playlist = playlist;
this._currentItem = 0;
this.play();
},
next: function() {
if (!this._playlist || !this._playlist.length)
return;
if (this._currentItem < this._playlist.length - 1) {
this._currentItem++;
this.play();
} else {
RadioTime.event.raise("playlistEnded");
}
},
play: function(url) {
if (url) {
this._playlist = [{"url":url}];
this._currentItem = 0;
}
var newUrl = "";
if (this._playlist) {
newUrl = this._playlist[this._currentItem].url;
}
// Don't stop unless the URL is different
if (newUrl != this._url) {
this.stop();
this._url = newUrl;
}
if (!this._url) {
return;
}
this._play(this._url);
},
isSupported: function() {
return true;
return ( //hack to add iphone support via quicktime by skipping flash
//FIXME: make player detection not need this. :-)
typeof RadioTime.player._player != "undefined" &&
(RadioTime.player._player.doStop || RadioTime.player._player.play)
);
}
},
addPlayer: function(player) {
this._players.unshift([function() { return true; }, player]);
},
_players: [
{
isSupported: function() {
return navigator.userAgent.match(/CE-HTML/);
},
implementation: {
init: function(container) {
this.playerName = "ce";
this.formats = ["mp3"];
var d = document.createElement("div");
this._id = RadioTime.makeId();
d.innerHTML = '<object id="' + this._id + '" type="audio/mpeg"></object>';
container.appendChild(d);
this._player = RadioTime.$(this._id);
},
_play: function(url){
if (!this._player || !this._player.play)
return;
this._player.data = this._url;
this._player.play(1);
var _this = this;
this._player.onPlayStateChange = function() {
if (5 == _this._player.playState) {
RadioTime.player.next();
}
RadioTime.event.raise("playstateChanged", RadioTime.player.states[_this._player.playState]);
}
},
stop: function() {
if (!this._player || !this._player.stop)
return;
this._player.stop();
},
pause: function() {
if (!this._player || !this._player.play)
return;
this._player.play();
},
states: {
5: "finished",
0: "stopped",
6: "error",
1: "playing",
2: "paused",
3: "connecting",
4: "buffering"
}
}
},
{
isSupported: function() { return window.songbird; },
implementation: { //FIXME: need to integrate more to do eventing based on player transitions.
// var listener = { observe: function(subject, topic, data) {...}}; songbird.addListener("faceplate.playing", listener)
init: function () {
this.playerName = 'songbird';
this.formats = ["mp3"];
songbird.setSiteScope("", "");
this.library = songbird.siteLibrary;
},
_play: function (url) {
//FIXME: it'd be nice to resume from pause (because it's faster),
// but that would mean juggling state w/ the host player (it could be paused on a local Library song)
//FIXME: switch to createMediaListFromURL? :-/
songbird.playURL(url);
//FIXME: need mediacore listener to sync w/ real state:
RadioTime.event.raise("playstateChanged", RadioTime.player.states[1]);
},
stop: function() {
songbird.stop();
RadioTime.event.raise("playstateChanged", RadioTime.player.states[0]);
},
pause: function() {
songbird.pause();
RadioTime.event.raise("playstateChanged", RadioTime.player.states[2]);
},
states: {
0: "stopped",
1: "playing",
2: "paused"
}
}
},
{
isSupported: function() { return true }, //FIXME: detect whether flash player is really available.
implementation:
{
init: function(container) {
this.playerName = 'flash';
this.formats = ["mp3", "flash"];
var d = document.createElement("div");
container.appendChild(d);
d.style.position = "absolute";
this._id = RadioTime.makeId();
var flashvars = '"autostart=true&objectid=' + this._id + '"';
if (/MSIE/.test(navigator.userAgent)) { // IE detection ~[-1]
d.innerHTML = '<object id="' + this._id + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="1" height="1"><param name="allowScriptAccess" value="always" /><param name="movie" value="' + RadioTime._path + 'swf/mplayer.swf?' + this._id + '" /><param name="flashvars" value=' + flashvars + '/></object>';
} else {
d.innerHTML = '<embed id="' + this._id + '" type="application/x-shockwave-flash" width="1" height="1" src="' + RadioTime._path + 'swf/mplayer.swf?' + this._id + '" allowscriptaccess="always" flashvars=' + flashvars + '/>';
}
container.innerHTML;
this._player = d.firstChild;
//this._player = RadioTime.$(this._id);
var _this = this;
RadioTime.event.subscribe("flashEvent", function(params) {
if (_this._id != params.objectid)
return;
switch (params.command) {
case "status":
if (5 == parseInt(params.arg)) {
RadioTime.debug("player next");
RadioTime.player.next();
}
RadioTime.debug("flashEvent status", params.arg);
RadioTime.event.raise("playstateChanged", RadioTime.player.states[params.arg]);
break;
case "progress":
case "position":
case "nowplaying":
break;
case "ready":
RadioTime.debug("flash object is ready");
break;
}
if (params.command != "position")
RadioTime.debug(params);
});
},
_play: function(url) {
if (!this._player || !this._player.playDirectUrl)
return;
this._player.playDirectUrl(url);
},
stop: function() {
if (!this._player || !this._player.doStop)
return;
this._player.doStop();
},
pause: function() {
if (!this._player || !this._player.doPause)
return;
this._player.doPause();
},
states: {
5: "finished",
0: "unknown",
1: "stopped",
2: "connecting",
3: "playing",
4: "error"
}
}
}
],
schedule: {
_tickInterval: 1, // seconds between Now playing progress updates
_tickReg: null, //non-null if progress is running
_fetchInterval: 10, // seconds between Next on updates
_fetchReg: null, //non-null if fetch is running
schedule: null,
nowPlayingIndex: -1,
guide_id: null,
init: function(guide_id) {
var _this = this;
this.stopUpdates();
this._fetch(guide_id);
},
_fetch: function(guide_id) {
RadioTime.debug("fetch with " + guide_id);
if (!guide_id) return;
if (this.lastUpdate && this.lastUpdate.getHours && this.lastUpdate.getHours() == RadioTime.now().getHours()){
this._available(this.schedule);
return;
}
var _this = this;
RadioTime.debug("RadioTime.API.getStationSchedule with " + guide_id);
RadioTime.API.getStationSchedule(function(data){
_this.guide_id = guide_id;
_this._available(data);
}, function() { RadioTime.debug("Failed to get schedule") }, guide_id);
this.lastUpdate = RadioTime.now();
},
/*
* Pre-process schedule
*/
_available: function(data) {
if (!data) return;
this.schedule = data;
var now = RadioTime.now();
var _this = this;
var oldNowPlayingIndex = (typeof this.nowPlayingIndex != "undefined") ? this.nowPlayingIndex : -2;
this.nowPlayingIndex = -1;
for (var i = 0; i < data.length; i++) {
// Skip the past
if (data[i].end < now.getTime()) {
continue;
}
// This is what playing now
if (data[i].start < now.getTime() && data[i].end > now.getTime()) {
this.nowPlayingIndex = i;
data[i].is_playing = true;
if (this._tickReg) {
clearInterval(this._tickReg);
}
this._tickReg = setInterval(function(){
_this._tick();
}, this._tickInterval*1000);
continue;
} else {
data[i].is_playing = false;
}
}
if (this._fetchReg) {
clearTimeout(this._fetchReg);
}
if (this.nowPlayingIndex < 0) { // Nothing is playing
this._fetchReg = setTimeout(function(){
_this._fetch(_this.guide_id);
}, this._fetchInterval*1000);
}
if (this.nowPlayingIndex != oldNowPlayingIndex) {
RadioTime.event.raise("schedule", data);
}
},
_tick: function() {
if (this.nowPlayingIndex < 0 || !this.schedule || !this.schedule[this.nowPlayingIndex]) {
return;
}
RadioTime.event.raise("scheduleProgress", {
start: this.schedule[this.nowPlayingIndex].start,
end: this.schedule[this.nowPlayingIndex].end
});
if (this.schedule[this.nowPlayingIndex].end < RadioTime.now().getTime()) {
this._available(this.schedule);
};
},
stopUpdates: function() {
if (this._tickReg) {
clearInterval(this._tickReg);
}
if (this._fetchReg) {
clearTimeout(this._fetchReg);
}
this.lastUpdate = null;
this.nowPlayingIndex = null;
this.guide_id = null;
}
},
logoSizes: {"square": "q", "small": "s", "normal": ""},
logoFormats: {"png":"png","gif":"gif"},
getLogoUrl: function(guide_id, logoSize, logoFormat) {
var logoSizeCode = RadioTime.logoSizes[logoSize] || "";
var logoFormat = RadioTime.logoFormats[logoFormat] || "png";
return "http://radiotime-logos.s3.amazonaws.com/" + guide_id + logoSizeCode + "." + logoFormat;
},
_formatReq: function(url, needAuth, data) {
// Prepare the URL
data = data || "";
// Avoid formatting it twice
if (url.url) {
return url;
}
if (url.indexOf("http") < 0) { // default request path
url = (needAuth ? "https://" : "http://") + RadioTime._baseUrl + url;
}
url += (url.indexOf("?")!=-1 ? "&" : "?");
if (url.indexOf("partnerId") < 0 && data.indexOf("partnerId") < 0) {
url += "partnerId=" + RadioTime._partnerId + "&";
}
if (url.indexOf("username") < 0 && url.indexOf("serial") < 0 && data.indexOf("serial") < 0) {
url += "serial=" + RadioTime._serial + "&";
}
if (!needAuth && RadioTime.formats && url.indexOf("formats") < 0 && data.indexOf("formats") < 0) {
url += "formats=" + RadioTime.formats.join(",") + "&";
}
if (RadioTime.latlon && url.indexOf("latlon") < 0 && data.indexOf("latlon") < 0) {
url += "latlon=" + RadioTime.latlon + "&";
if (RadioTime._exactLocation && url.indexOf("exact") < 0 && data.indexOf("exact") < 0) {
url += "exact=1&"
}
}
if (!needAuth && RadioTime.locale && url.indexOf("locale") < 0 && data.indexOf("locale") < 0) {
url += "locale=" + RadioTime.locale + "&";
}
if (-1 == url.indexOf("render=json")) {
url += "render=json&";
}
return {"url": url, "data": data};
},
loadJSON: function(url, onsuccess, onfailure) {
url = RadioTime._formatReq(url);
RadioTime.debug("API request: " + url.url);
RadioTime._loader.sendRequest(url, function(data) {
var status = (data.head && data.head.status) ? data.head.status : "missing";
if (status == "200") { // Status is not returned for Register.aspx call
if (data && onsuccess) {
onsuccess.call(this, data.body, data.head);
}
} else {
if (onfailure) onfailure.call(null, data.head);
}
RadioTime.event.raise("loaded");
}, function() {
if (onfailure) onfailure.call(null);
RadioTime.event.raise("failed", url);
});
},
_getIdType: function(guideId) {
if (!guideId) return "unknown";
switch (guideId.charAt(0)) {
case "p":
return "program";
case "s":
return "station";
case "g":
return "group";
case "t":
return "topic";
case "c":
return "category";
case "r":
return "region";
case "f":
return "podcast_category"; //???
case "a":
return "affiliate";
case "e":
return "stream";
default:
return "unknown";
}
},
now: function() {
return (
new Date(
(+new Date()) +
this.timeCorrection +
(this.gmtOffset + (new Date()).getTimezoneOffset())*60*1000
)
);
},
_dateToYYYYMMDD: function(date) {
var out = '';
out += date.getFullYear();
var mon = date.getMonth() + 1;
out += (mon < 10) ? "0" + mon : mon;
var dat = date.getDate();
out += (dat < 10) ? "0" + dat : dat;
return out;
},
formatTime: function(time) {
if (typeof time != "object") {
var ts = time;
time = RadioTime.now();
time.setTime(ts);
}
var out = '';
if (RadioTime._useAMPM) {
var hours = time.getHours();
var suffix = "am";
switch (true) {
case (hours == 0) :
hours = 12;
suffix = "am";
break;
case (hours == 12):
suffix = "pm";
break;
case (hours > 12):
suffix = "pm";
hours -= 12
break
default:
break;
}
out = (hours + 0.01*time.getMinutes()).toFixed(2).replace(".", ":") + suffix;
} else {
out = (time.getHours() + 0.01*time.getMinutes()).toFixed(2).replace(".", ":");
}
return out.replace(/^(\d):/, '0$1:');
},
_dateFromServicesString: function(dateString) {
var out = new Date(dateString.replace("T", " ").replace(/-/g, "/"));
out.setTime(out.getTime());
return out;
},
_calculateEndTime: function(startTime, duration /*seconds*/) {
var endTime = RadioTime.now();
if (isNaN(startTime)) startTime = startTime.getTime();
endTime.setTime(startTime + duration*1000);
return endTime;
},
_histories: { //TODO (SDK) switch to hash-tag history system to allow browser back/forward to work.
"internal": {
_history: [],
_equals: function(o1, o2) {
return (o1.URL == o2.URL);
},
_init: function(onHistoryChange) {
this.onHistoryChange = onHistoryChange;
},
back: function() {
if (this._history.length > 0) {
this._history.pop();
this.onHistoryChange(this.last());
return true;
} else {
return false;
}
},
add: function(object){
RadioTime.debug("history add");
RadioTime.debug(object);
//if (!this.history.length || !this._equals(this.last(), object)) {
object.restorePoint = false;
this._history.push(object);
//}
},
last: function() {
RadioTime.debug("history last");
return (this._history.length > 0) ? this._history[this._history.length - 1] : null;
},
reset: function() {
RadioTime.debug("history clear");
while(this._history.length > 2) { //FIXME: CE assuming first = home is bad for general SDK apps.
RadioTime.debug("... back");
this._history.pop();
}
},
createRestorePoint: function() {
if (this.last()) {
this.last().restorePoint = true;
}
},
restore: function() {
var hasRestorePoint = false;
for (var i = this._history.length - 1; i >=0; i--) {
if (this._history[i].restorePoint){
//this.history[i].restorePoint = false;
this._history = this._history.slice(0, i + 1);
break;
}
}
}
},
'hash': { //FIXME: assuming (as RSH does) that the hash is ours to use is bad for multi-widget pages.
_seq: 0, //used to make a unique hash for browser-based history.
_restores: {},
_init: function(onHistoryChange) {
dhtmlHistory.initialize();
dhtmlHistory.addListener(function(newLocation, historyData) {
RadioTime.history._seq = RadioTime.history._parseSequence(newLocation) + 1;
if (onHistoryChange) {
onHistoryChange(historyData);
}
})
},
_makeHash: function(seq) {
return "history" + seq;
},
_parseSequence: function(hash) {
if (-1 == hash.indexOf("history")) {
return 0;
} else {
return parseInt(hash.replace("history",""));
}
},
back: function() {
window.history.back();
},
add: function(obj) {
var hash = this._makeHash(this._seq++);
dhtmlHistory.add(hash, obj);
},
last: function() {
var key = dhtmlHistory.getCurrentLocation();
if (historyStorage.hasKey(key)) {
return historyStorage.get(dhtmlHistory.getCurrentLocation());
} else {
return null;
}
},
reset: function() {
//this._seq = 0;
//this.restores = {};
//window.location.hash = "";
}, //no-op because browser history can handle it (and RSH doesn't have an easy way to clear).
createRestorePoint: function() {
if (this._seq > 0) {
this._restores[this._seq] = true;
}
},
restore: function() {
var hasRestorePoint = false;
for (var i = his._seq; i >=0; i--) {
if (this._restores[i]){
this._seq = i;
window.location.hash = "#" + this._seq;
}
}
}
}
},
_isArray: function(v) {
return v && typeof v === 'object' && typeof v.length === 'number' &&
!(v.propertyIsEnumerable('length'));
},
_isString: function(it) {
return (typeof it == "string" || it instanceof String);
},
_hitch: function(scope, method) { //From Dojo Toolkit, returns a function which executes with "this" bound to scope.
if(_isString(method)){ //more info on why it's needed: http://www.quirksmode.org/js/this.html
scope = scope || window;
return function(){ return scope[method].apply(scope, arguments || []); };
}
return function(){ return method.apply(scope, arguments || []); };
},
getTuneUrl: function(guideId) {
return this._formatReq("Tune.ashx?id=" + guideId).url;
},
API: {
getCategory: function(success, failure, category) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Browse.ashx?c=" + category, success, failure);
},
getRootMenu: function(success, failure) {
RadioTime.event.raise("loading", 'status_loading_menu');
RadioTime.loadJSON("Browse.ashx", success, failure);
},
getStationSchedule: function(success, failure, id){ //TODO (SDK) - add optional time range.
var startDate = RadioTime.now();
var stopDate = RadioTime.now();
stopDate.setTime(startDate.getTime() + 1000 * 60 * 60 * 24);
startDate.setTime(startDate.getTime() - 1000 * 60 * 60 * 24);
//FIXME: seems we should either autodetect (as here) or use offset (as RT getTime above), but not both.
var url = "Browse.ashx?c=schedule&id=" + id + "&start=" + RadioTime._dateToYYYYMMDD(startDate) +
"&stop=" + RadioTime._dateToYYYYMMDD(stopDate) + "&autodetect=true";// + "&offset=" + RadioTime.gmtOffset;
RadioTime.event.raise("loading", 'status_loading_schedule');
RadioTime.loadJSON(url, function(data) {
var now = RadioTime.now().getTime();
// Pre-process the data
for (var i = 0; i < data.length; i++) {
data[i].start = RadioTime._dateFromServicesString(data[i].start).getTime();
data[i].end = RadioTime._calculateEndTime(data[i].start, data[i].duration).getTime();
data[i].is_playing = (data[i].start < now) && (data[i].end > now);
var str = RadioTime.formatTime(data[i].start);
data[i].timeSpanString = str;
data[i].index = i;
data[i].oType = RadioTime._getIdType(data[i].guide_id);
}
success.call(this, data);
}, failure);
},
getProgramListeningOptions: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Tune.ashx?c=sbrowse&flatten=true&id=" + id, success, failure);
},
describe: function(success, failure, id){
RadioTime.event.raise("loading", 'status_finding_stations');
RadioTime.loadJSON("Describe.ashx?id=" + id, success, failure);
},
tune: function(success, failure, guideId) {
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON(RadioTime.getTuneUrl(guideId), success, failure);
},
getOptions: function(success, failure, id){
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Options.ashx?id=" + id, success, failure);
},
getRelated: function(success, failure, id){
RadioTime.event.raise("loading", 'status_loading');
RadioTime.loadJSON("Browse.ashx?id=" + id, success, failure);
},
addPreset: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_adding_preset');
var url = RadioTime._formatReq("Preset.ashx?c=add&id=" + id, true);
RadioTime.loadJSON(url, success, failure)
},
removePreset: function(success, failure, id) {
RadioTime.event.raise("loading", 'status_removing_preset');
var url = RadioTime._formatReq("Preset.ashx?c=remove&id=" + id, true);
RadioTime.loadJSON(url, success, failure)
},
search: function(success, failure, query, filter) {
RadioTime.event.raise("loading", 'status_searching');
var url = RadioTime._formatReq("Search.ashx?query=" + query + "&filter=" + filter);
RadioTime.loadJSON(url, success, failure)
},
getAccountStatus: function(success, failure) {
RadioTime.event.raise("loading", 'status_checking_account');
var url = RadioTime._formatReq("Account.ashx?c=query", true);
RadioTime.loadJSON(url, function(data){
var out = {
"hasAccount": true,
"text": data[0].text
}
success.call(this, out);
}, function(){
var u = RadioTime._formatReq("Account.ashx?c=claim", true);
RadioTime.loadJSON(u, function(data){
var out = {
"hasAccount": false,
"text": data[0].text
}
success.call(this, out);
}, failure);
});
},
getLocalStrings: function(success, failure) {
RadioTime.event.raise("loading", 'status_loading');
var url = RadioTime._formatReq("Config.ashx?c=contentQuery");
RadioTime.loadJSON(url, function(data) {
RadioTime._applyLocalStrings(data);
success(data);
}, failure);
},
getTime: function(success, failure) {
RadioTime.event.raise("loading", 'status_sync_time');
var url = RadioTime._formatReq("Config.ashx?c=time");
RadioTime.loadJSON(url, success, failure)
}
},
response: {
audio: function (body) {
var out = [];
RadioTime._walk(body,
function(elem) {
if (elem.element == "outline" && elem.type == "audio") {
out.push(elem);
}
}
);
return out;
},
flatten: function (data, copyKey) {
var out = [];
for (var i = 0; i < data.length; i++ ) {
out.push(data[i]);
if (data[i].children) {
if (data[i].key && copyKey) {
for (var j in data[i].children) {
data[i].children[j].key = data[i].key;
}
}
out = out.concat(this.flatten(data[i].children, copyKey));
}
}
return out;
},
station: function(body) {
var out = [];
var inStationsDepth = -1;
RadioTime._walk(body,
function(elem, depth) {
if (inStationsDepth > depth) {
inStationsDepth = -1;
return
};
if (elem.key == 'stations') {
inStationsDepth = depth + 1;
return;
}
if (inStationsDepth > -1) {
out.push(elem);
} else {
if (RadioTime._getIdType(elem.guide_id) == "station") {
out.push(elem);
}
}
}
);
return out;
}
},
_walk: function(tree, handler, depth) {
depth = depth || 0;
if (RadioTime._isArray(tree)) {
for (var i=0; i < tree.length; i++) {
RadioTime._walk(tree[i], handler, depth);
}
} else {
handler(tree, depth);
if (tree.children) {
RadioTime._walk(tree.children, handler, depth + 1);
}
}
},
_applyLocalStrings: function(locale) {
var out = {};
for (var i in locale) {
out[locale[i].key] = locale[i].value;
}
RadioTime.merge(out, RadioTime.localStrings);
RadioTime.localStrings = out;
RadioTime.event.raise("localStrings");
},
_loader: {
_requestTimeout: 30, // in seconds
requests: {},
sendRequest: function(req, success, failure, retries) {
if (typeof req != 'number') { // this is a new request
var reqId = RadioTime.makeId();
this.requests[reqId] = {
_req: req,
_requestCompleted: false,
_callback: success != undefined ? success : null,
_failure: failure != undefined ? failure : null,
_retries: retries != undefined ? retries : 0,
_reqUrl: (req.url.indexOf("callback=") < 0) ? req.url + "callback=RadioTime._loader.requests[" + reqId + "].init" : req.url,
init: function(data) {
this._requestCompleted = true;
if (this._callback) {
this._callback.call(this, data);
}
},
fail: function() {
if (this._failure) {
this._failure.call(this);
}
}
};
} else {
var reqId = req;
if (this.requests[reqId] == undefined)
return;
// OK
if (this.requests[reqId]._requestCompleted) {
this.clearRequest(reqId);
return;
}
// No retries left?
if (this.requests[reqId]._retries <= 0) {
this.onerror(this.requests[reqId]);
this.clearRequest(reqId);
return;
}
this.requests[reqId]._retries--;
}
if (RadioTime.$(reqId)) {
RadioTime.$(reqId).parentNode.removeChild(RadioTime.$(reqId));
}
var s;
var _this = this;
if (this.requests[reqId]._callback) {
s = document.createElement("script");
s.onload = function() {
}
} else { // use iframe if we don't care about result
s = document.createElement("iframe");
s.style.visibility = "hidden";
s.style.width = "1px";
s.style.height = "1px";
s.onload = function() {
_this.clearRequest(this.id);
}
}
s.id = reqId;
s.src = this.requests[reqId]._reqUrl;
RadioTime._container.appendChild(s);
setTimeout(function() {
_this.sendRequest(reqId);
}, this._requestTimeout*1000);
},
clearRequest: function(reqId) {
if (RadioTime.$(reqId)) {
RadioTime.$(reqId).parentNode.removeChild(RadioTime.$(reqId));
delete this.requests[reqId];
} else {
if (this.requests[reqId] && !this.requests[reqId]._requestCompleted) {
var _this = this;
this.requests[reqId].init = function(data){
RadioTime.debug("Late request arrived: " + reqId);
_this.clearRequest(reqId);
}
}
}
},
onerror: function(req) {
req.fail();
}
},
event: {
_handlers: [],
_hid: 0,
subscribe: function (eventName, handler, forObj) {
if (!this._handlers[eventName]) {
this._handlers[eventName] = [];
}
var h = {};
h.func = handler;
h.forObj = forObj; // if obj is "undefined" then treat handler as default
h.id = this._hid++;
this._handlers[eventName].push(h);
return h.id;
},
unsubscribe: function(hid) {
for (var event_ in this._handlers) {
for (var handler in this._handlers[event_]) {
if (this._handlers[event_][handler].id == hid) {
this._handlers[event_].splice(handler, 1);
return true;
}
}
}
return false;
},
raise: function(eventName, params, toObj) {
if (!RadioTime._enableEvents) return true;
if (!this._handlers[eventName]) {
//RadioTime.debug("No handlers for " + eventName, "warning")
return true;
}
var eh = this._handlers[eventName];
for (handler in eh) {
if (eh[handler].func && (eh[handler].forObj == toObj || eh[handler].forObj == undefined)) {
eh[handler].func.call(eh[handler].forObj, params);
}
}
}
},
$: function(name) {
var el = document.getElementById(name);
if (!el) {
RadioTime.debug('Element "',name, '" is not found');
}
return el;
},
/*
* Get localized string
*/
L: function(token) {
return this.localStrings[token] || token;
},
localStrings: {},
debug: function(){
if (!RadioTime._verbose) return;
if (arguments.length == 1) {
var txt = arguments[0];
} else {
var txt = Array.prototype.slice.call(arguments).join(" ");
}
if (window.console && console.debug) {
console.debug.apply(console, arguments);
} else {
// Can't use RadioTime.$ here because it would cause infinite recruision
// and stack overflow due to the debug() call in RadioTime.$
if (document.getElementById("radiotime_log")) {
document.getElementById("radiotime_log").innerHTML += txt + ", ";
}
}
},
makeId: function() {
return 1*(Math.random().toString().replace('.', ''));
},
_trim: function(s) {
return s.match(/^\s*(.*?)\s*$/)[1];
},
merge: function(target, source, useSuper){
if (useSuper) {
target.SUPER = {};
target.callSuper = function() {
var function_name = arguments[0];
[].unshift.call(arguments, this);
if (typeof this.SUPER[function_name] != "undefined") {
return this.SUPER[function_name].apply(this, arguments);
} else {
return false;
}
}
}
for (var i in source){
if (!target[i]) {
target[i] = source[i];
} else if (useSuper) {
target.SUPER[i] = source[i];
}
}
},
cookie: {
save: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
read: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
clear: function (name) {
this.save(name,"",-1);
}
},
/**
* This function is called from Flash
* @param {Object} command
* @param {Object} arg
* @param {Object} objectid
*/
getUpdate: function(command, arg, objectid) {
var params ={
"command": command,
"arg": arg,
"objectid": objectid
}
RadioTime.event.raise("flashEvent", params);
}
}
| Added HTML5 audio support (for iPad only for now). | clients/js/src/js/radiotime.js | Added HTML5 audio support (for iPad only for now). | <ide><path>lients/js/src/js/radiotime.js
<ide> this._play(this._url);
<ide> },
<ide> isSupported: function() {
<del> return true;
<del> return ( //hack to add iphone support via quicktime by skipping flash
<del> //FIXME: make player detection not need this. :-)
<del> typeof RadioTime.player._player != "undefined" &&
<del> (RadioTime.player._player.doStop || RadioTime.player._player.play)
<del> );
<add> return !!this._play;
<ide> }
<ide> },
<ide> addPlayer: function(player) {
<ide> pause: function() {
<ide> if (!this._player || !this._player.play)
<ide> return;
<del> this._player.play();
<add> this._player.play(); // this actually means 'pause' on CE!
<ide> },
<ide>
<ide> states: {
<ide> }
<ide> },
<ide> {
<del> isSupported: function() { return true }, //FIXME: detect whether flash player is really available.
<add> isSupported: function() {
<add> var f = "-", n = navigator;
<add> if (n.plugins && n.plugins.length) {
<add> for (var ii=0; ii<n.plugins.length; ii++) {
<add> if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
<add> f = n.plugins[ii].description.split('Shockwave Flash ')[1];
<add> break;
<add> }
<add> }
<add> } else if (window.ActiveXObject) {
<add> for (var ii=10; ii>=2; ii--) {
<add> try {
<add> var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + ii + "');");
<add> if (fl) {
<add> f = ii + '.0';
<add> break;
<add> }
<add> }
<add> catch(e) {}
<add> }
<add> }
<add> if (f.split(".")[0]) {
<add> f = f.split(".")[0];
<add> }
<add> return (f > 8);
<add> },
<ide> implementation:
<ide> {
<ide> init: function(container) {
<ide> 4: "error"
<ide> }
<ide> }
<add> },{
<add> isSupported: function() {
<add> // iPad-only for now
<add> return /iPad/i.test(navigator.userAgent);
<add> },
<add> implementation: {
<add> init: function(container){
<add> this.playerName = "html5";
<add> this.formats = ["mp3", "aac"];
<add> var d = new Audio();
<add> this._id = RadioTime.makeId();
<add> d.id = this._id;
<add> container.appendChild(d);
<add> this._player = RadioTime.$(this._id);
<add> var _this = this;
<add> /*
<add> * <audio> event handlers
<add> */
<add> this._player.addEventListener('error', function(){
<add> _this._stateChanged('error');
<add> }, true);
<add> this._player.addEventListener('playing', function(){
<add> _this._stateChanged('playing');
<add> }, true);
<add> this._player.addEventListener('pause', function(){
<add> _this._stateChanged('pause');
<add> }, true);
<add> this._player.addEventListener('ended', function(){
<add> _this._stateChanged('ended');
<add> RadioTime.player.next();
<add> }, true);
<add> this._player.addEventListener('abort', function(){
<add> _this._stateChanged('abort');
<add> }, true);
<add> this._player.addEventListener('loadstart', function(){
<add> _this._stateChanged('loadstart');
<add> }, true);
<add> this._player.addEventListener('seeking', function(){
<add> _this._stateChanged('seeking');
<add> }, true);
<add> this._player.addEventListener('waiting', function(){
<add> _this._stateChanged('waiting');
<add> }, true);
<add> this._player.addEventListener('suspend', function(){
<add> _this._stateChanged('suspend');
<add> }, true);
<add> this._player.addEventListener('stalled', function(){
<add> _this._stateChanged('stalled');
<add> }, true);
<add> },
<add> _stateChanged: function(newstate){
<add> var state = "stopped";
<add> switch (newstate) {
<add> case "pause":
<add> state = "paused";
<add> break;
<add> case "stalled":
<add> case "suspend":
<add> case "ended":
<add> case "stopped":
<add> state = "stopped";
<add> break;
<add> case "playing":
<add> state = "playing";
<add> break;
<add> case "loadstart":
<add> case "waiting":
<add> case "seeking":
<add> state = "connecting";
<add> break;
<add> case "error":
<add> state = "error";
<add> break;
<add> }
<add> RadioTime.event.raise("playstateChanged", RadioTime.player.states[state]);
<add> },
<add> _play: function(url){
<add> if (this._player.src != url) {
<add> this._player.src = this._url;
<add> this._player.load();
<add> }
<add> this._player.play();
<add> },
<add> stop: function(){
<add> this._player.pause();
<add> },
<add> pause: function(){
<add> this._player.pause();
<add> },
<add> states: {
<add> "finished": "finished",
<add> "stopped": "stopped",
<add> "error": "error",
<add> "playing": "playing",
<add> "paused": "paused",
<add> "connecting": "connecting"
<add> }
<add> }
<ide> }
<ide> ],
<ide> schedule: { |
|
Java | mit | e2fb7fad37d85035e45c1126718b9f4918b733af | 0 | mwcaisse/AndroidFT,mwcaisse/AndroidFT,mwcaisse/AndroidFT | /**
*
*/
package com.ricex.aft.servlet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ricex.aft.common.entity.File;
import com.ricex.aft.servlet.manager.FileManager;
/**
* File Controller for uploading files and retreiving files
*
* @author Mitchell Caisse
*
*/
@Controller
@RequestMapping("/file")
public class FileController {
/** The file manager that wil be used to fetch files */
private FileManager fileManager;
public FileController() {
fileManager = FileManager.INSTANCE;
}
/** Retreives the information about the file with the given id
*
* @param fileId The id of the file to fetch
* @return The information about the file
*/
@RequestMapping(value = "/info/{fileId}", method = RequestMethod.GET, produces={"application/json"})
public @ResponseBody File getFile(@PathVariable long fileId) {
return fileManager.getFile(fileId);
}
/** Returns the contents of the file with the specified id
*
* @param fileId The id of the file contents to fetch
* @return The raw bytes of the file
*/
@RequestMapping(value = "/contents/{fileId}", method = RequestMethod.GET, produces={"application/octet-stream"})
public @ResponseBody File getFileContents(@PathVariable long fileId) {
return fileManager.getFile(fileId);
}
/** Uploads the given file, and assigns it an id
* *
* @param fileContents The contents of the file to upload
* @param fileName The name of the file
* @return The id of the uploaded file
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes={"application/json"})
public @ResponseBody long createFile(@RequestBody byte[] fileContents, @RequestParam(value="fileName", required = true) String fileName) {
return fileManager.createFile(fileContents,fileName);
}
}
| aft-servlet/src/main/java/com/ricex/aft/servlet/controller/FileController.java | /**
*
*/
package com.ricex.aft.servlet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ricex.aft.common.entity.File;
import com.ricex.aft.servlet.manager.FileManager;
/**
* File Controller for uploading files and retreiving files
*
* @author Mitchell Caisse
*
*/
@Controller
@RequestMapping("/file")
public class FileController {
/** The file manager that wil be used to fetch files */
private FileManager fileManager;
public FileController() {
fileManager = FileManager.INSTANCE;
}
/** Retreives the information about the file with the given id
*
* @param fileId The id of the file to fetch
* @return The information about the file
*/
@RequestMapping(value = "/info/{fileId}", method = RequestMethod.GET, produces={"application/json"})
public @ResponseBody File getFile(@PathVariable long fileId) {
return fileManager.getFile(fileId);
}
/** Returns the contents of the file with the specified id
*
* @param fileId The id of the file contents to fetch
* @return The raw bytes of the file
*/
@RequestMapping(value = "/contents/{fileId}", method = RequestMethod.GET, produces={"application/octet-stream"})
public @ResponseBody File getFileContents(@PathVariable long fileId) {
return fileManager.getFile(fileId);
}
/** Retrieves the name of the file with the given id
*
* @param fileId The id of the file to fetch
* @return The name of the file
*/
@RequestMapping(value = "/name/{fileId}", method = RequestMethod.GET, produces={"application/json"})
public @ResponseBody String getFileName(@PathVariable long fileId) {
return fileManager.getFile(fileId).getFileName();
}
/** Uploads the given file, and assigns it an id
* *
* @param fileContents The contents of the file to upload
* @param fileName The name of the file
* @return The id of the uploaded file
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes={"application/json"})
public @ResponseBody long createFile(@RequestBody byte[] fileContents, @RequestParam(value="fileName", required = true) String fileName) {
return fileManager.createFile(fileContents,fileName);
}
}
| Actualy saved the FileController this time
| aft-servlet/src/main/java/com/ricex/aft/servlet/controller/FileController.java | Actualy saved the FileController this time | <ide><path>ft-servlet/src/main/java/com/ricex/aft/servlet/controller/FileController.java
<ide> return fileManager.getFile(fileId);
<ide> }
<ide>
<del> /** Retrieves the name of the file with the given id
<del> *
<del> * @param fileId The id of the file to fetch
<del> * @return The name of the file
<del> */
<del>
<del> @RequestMapping(value = "/name/{fileId}", method = RequestMethod.GET, produces={"application/json"})
<del> public @ResponseBody String getFileName(@PathVariable long fileId) {
<del> return fileManager.getFile(fileId).getFileName();
<del> }
<del>
<ide> /** Uploads the given file, and assigns it an id
<ide> * *
<ide> * @param fileContents The contents of the file to upload |
|
JavaScript | agpl-3.0 | ef3eebfd3e46276aa58d722e4e8986946872439c | 0 | IljaN/core,michaelletzgus/nextcloud-server,IljaN/core,jbicha/server,sharidas/core,whitekiba/server,pmattern/server,pollopolea/core,lrytz/core,sharidas/core,sharidas/core,nextcloud/server,andreas-p/nextcloud-server,whitekiba/server,bluelml/core,xx621998xx/server,cernbox/core,pmattern/server,bluelml/core,whitekiba/server,nextcloud/server,pollopolea/core,IljaN/core,pixelipo/server,pollopolea/core,andreas-p/nextcloud-server,michaelletzgus/nextcloud-server,sharidas/core,owncloud/core,endsguy/server,jbicha/server,michaelletzgus/nextcloud-server,xx621998xx/server,pollopolea/core,andreas-p/nextcloud-server,Ardinis/server,cernbox/core,pollopolea/core,whitekiba/server,lrytz/core,owncloud/core,bluelml/core,nextcloud/server,endsguy/server,pmattern/server,pixelipo/server,sharidas/core,xx621998xx/server,pixelipo/server,michaelletzgus/nextcloud-server,IljaN/core,Ardinis/server,pmattern/server,lrytz/core,IljaN/core,cernbox/core,jbicha/server,lrytz/core,Ardinis/server,pmattern/server,andreas-p/nextcloud-server,endsguy/server,bluelml/core,owncloud/core,owncloud/core,whitekiba/server,jbicha/server,xx621998xx/server,lrytz/core,bluelml/core,jbicha/server,endsguy/server,phil-davis/core,cernbox/core,cernbox/core,xx621998xx/server,owncloud/core,nextcloud/server,Ardinis/server,endsguy/server,pixelipo/server,andreas-p/nextcloud-server,pixelipo/server,Ardinis/server | FileList={
useUndo:true,
update:function(fileListHtml) {
$('#fileList').empty().html(fileListHtml);
},
addFile:function(name,size,lastModified,loading){
var img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file.png');
var html='<tr data-type="file" data-size="'+size+'">';
if(name.indexOf('.')!=-1){
var basename=name.substr(0,name.lastIndexOf('.'));
var extension=name.substr(name.lastIndexOf('.'));
}else{
var basename=name;
var extension=false;
}
html+='<td class="filename" style="background-image:url('+img+')"><input type="checkbox" />';
html+='<a class="name" href="download.php?file='+$('#dir').val().replace(/</, '<').replace(/>/, '>')+'/'+name+'"><span class="nametext">'+basename
if(extension){
html+='<span class="extension">'+extension+'</span>';
}
html+='</span></a></td>';
if(size!='Pending'){
simpleSize=simpleFileSize(size);
}else{
simpleSize='Pending';
}
sizeColor = Math.round(200-size/(1024*1024)*2);
lastModifiedTime=Math.round(lastModified.getTime() / 1000);
modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
html+='<td class="filesize" title="'+humanFileSize(size)+'" style="color:rgb('+sizeColor+','+sizeColor+','+sizeColor+')">'+simpleSize+'</td>';
html+='<td class="date"><span class="modified" title="'+formatDate(lastModified)+'" style="color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')">'+relative_modified_date(lastModified.getTime() / 1000)+'</span></td>';
html+='</tr>';
FileList.insertElement(name,'file',$(html).attr('data-file',name));
if(loading){
$('tr').filterAttr('data-file',name).data('loading',true);
}else{
$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions);
}
},
addDir:function(name,size,lastModified){
html = $('<tr></tr>').attr({ "data-type": "dir", "data-size": size, "data-file": name});
td = $('<td></td>').attr({"class": "filename", "style": 'background-image:url('+OC.imagePath('core', 'filetypes/folder.png')+')' });
td.append('<input type="checkbox" />');
var link_elem = $('<a></a>').attr({ "class": "name", "href": OC.linkTo('files', 'index.php')+"&dir="+ encodeURIComponent($('#dir').val()+'/'+name).replace(/%2F/g, '/') });
link_elem.append($('<span></span>').addClass('nametext').text(name));
link_elem.append($('<span></span>').attr({'class': 'uploadtext', 'currentUploads': 0}));
td.append(link_elem);
html.append(td);
if(size!='Pending'){
simpleSize=simpleFileSize(size);
}else{
simpleSize='Pending';
}
sizeColor = Math.round(200-Math.pow((size/(1024*1024)),2));
lastModifiedTime=Math.round(lastModified.getTime() / 1000);
modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*5);
td = $('<td></td>').attr({ "class": "filesize", "title": humanFileSize(size), "style": 'color:rgb('+sizeColor+','+sizeColor+','+sizeColor+')'}).text(simpleSize);
html.append(td);
td = $('<td></td>').attr({ "class": "date" });
td.append($('<span></span>').attr({ "class": "modified", "title": formatDate(lastModified), "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')' }).text( relative_modified_date(lastModified.getTime() / 1000) ));
html.append(td);
FileList.insertElement(name,'dir',html);
$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions);
$('tr').filterAttr('data-file',name).find('td.filename').droppable(folderDropOptions);
},
refresh:function(data) {
result = jQuery.parseJSON(data.responseText);
if(typeof(result.data.breadcrumb) != 'undefined'){
updateBreadcrumb(result.data.breadcrumb);
}
FileList.update(result.data.files);
resetFileActionPanel();
},
remove:function(name){
$('tr').filterAttr('data-file',name).find('td.filename').draggable('destroy');
$('tr').filterAttr('data-file',name).remove();
if($('tr[data-file]').length==0){
$('#emptyfolder').show();
$('.file_upload_filename').addClass('highlight');
}
},
insertElement:function(name,type,element){
//find the correct spot to insert the file or folder
var fileElements=$('tr[data-file][data-type="'+type+'"]');
var pos;
if(name.localeCompare($(fileElements[0]).attr('data-file'))<0){
pos=-1;
}else if(name.localeCompare($(fileElements[fileElements.length-1]).attr('data-file'))>0){
pos=fileElements.length-1;
}else{
for(var pos=0;pos<fileElements.length-1;pos++){
if(name.localeCompare($(fileElements[pos]).attr('data-file'))>0 && name.localeCompare($(fileElements[pos+1]).attr('data-file'))<0){
break;
}
}
}
if(fileElements.length){
if(pos==-1){
$(fileElements[0]).before(element);
}else{
$(fileElements[pos]).after(element);
}
}else if(type=='dir' && $('tr[data-file]').length>0){
$('tr[data-file]').first().before(element);
}else{
$('#fileList').append(element);
}
$('#emptyfolder').hide();
$('.file_upload_filename').removeClass('highlight');
},
loadingDone:function(name){
var tr=$('tr').filterAttr('data-file',name);
tr.data('loading',false);
var mime=tr.data('mime');
tr.attr('data-mime',mime);
getMimeIcon(mime,function(path){
tr.find('td.filename').attr('style','background-image:url('+path+')');
});
tr.find('td.filename').draggable(dragOptions);
},
isLoading:function(name){
return $('tr').filterAttr('data-file',name).data('loading');
},
rename:function(name){
var tr=$('tr').filterAttr('data-file',name);
tr.data('renaming',true);
var td=tr.children('td.filename');
var input=$('<input class="filename"></input>').val(name);
var form=$('<form></form>')
form.append(input);
td.children('a.name').text('');
td.children('a.name').append(form)
input.focus();
form.submit(function(event){
event.stopPropagation();
event.preventDefault();
var newname=input.val();
if (newname != name) {
if ($('tr').filterAttr('data-file', newname).length > 0) {
$('#notification').html(newname+' '+t('files', 'already exists')+'<span class="replace">'+t('files', 'replace')+'</span><span class="cancel">'+t('files', 'cancel')+'</span>');
$('#notification').data('oldName', name);
$('#notification').data('newName', newname);
$('#notification').fadeIn();
newname = name;
} else {
$.get(OC.filePath('files','ajax','rename.php'), { dir : $('#dir').val(), newname: newname, file: name },function(result) {
if (!result || result.status == 'error') {
OC.dialogs.alert(result.data.message, 'Error moving file');
newname = name;
}
});
}
}
tr.attr('data-file', newname);
var path = td.children('a.name').attr('href');
td.children('a.name').attr('href', path.replace(encodeURIComponent(name), encodeURIComponent(newname)));
if (newname.indexOf('.') > 0) {
var basename=newname.substr(0,newname.lastIndexOf('.'));
} else {
var basename=newname;
}
td.children('a.name').empty();
var span=$('<span class="nametext"></span>');
span.text(basename);
td.children('a.name').append(span);
if (newname.indexOf('.') > 0) {
span.append($('<span class="extension">'+newname.substr(newname.lastIndexOf('.'))+'</span>'));
}
tr.data('renaming',false);
return false;
});
input.click(function(event){
event.stopPropagation();
event.preventDefault();
});
input.blur(function(){
form.trigger('submit');
});
},
replace:function(oldName, newName) {
// Finish any existing actions
if (FileList.lastAction || !FileList.useUndo) {
FileList.lastAction();
}
var tr = $('tr').filterAttr('data-file', oldName);
tr.hide();
FileList.replaceCanceled = false;
FileList.replaceOldName = oldName;
FileList.replaceNewName = newName;
FileList.lastAction = function() {
FileList.finishReplace();
};
$('#notification').html(t('files', 'replaced')+' '+newName+' '+t('files', 'with')+' '+oldName+'<span class="undo">'+t('files', 'undo')+'</span>');
$('#notification').fadeIn();
},
finishReplace:function() {
if (!FileList.replaceCanceled && FileList.replaceOldName && FileList.replaceNewName) {
// Delete the file being replaced and rename the replacement
FileList.deleteCanceled = false;
FileList.deleteFiles = [FileList.replaceNewName];
FileList.finishDelete(function() {
$.ajax({url: OC.filePath('files', 'ajax', 'rename.php'), async: false, data: { dir: $('#dir').val(), newname: FileList.replaceNewName, file: FileList.replaceOldName }, success: function(result) {
if (result && result.status == 'success') {
var tr = $('tr').filterAttr('data-file', FileList.replaceOldName);
tr.attr('data-file', FileList.replaceNewName);
var td = tr.children('td.filename');
td.children('a.name .span').text(FileList.replaceNewName);
var path = td.children('a.name').attr('href');
td.children('a.name').attr('href', path.replace(encodeURIComponent(FileList.replaceOldName), encodeURIComponent(FileList.replaceNewName)));
if (FileList.replaceNewName.indexOf('.') > 0) {
var basename = FileList.replaceNewName.substr(0, FileList.replaceNewName.lastIndexOf('.'));
} else {
var basename = FileList.replaceNewName;
}
td.children('a.name').empty();
var span = $('<span class="nametext"></span>');
span.text(basename);
td.children('a.name').append(span);
if (FileList.replaceNewName.indexOf('.') > 0) {
span.append($('<span class="extension">'+FileList.replaceNewName.substr(FileList.replaceNewName.lastIndexOf('.'))+'</span>'));
}
tr.show();
} else {
OC.dialogs.alert(result.data.message, 'Error moving file');
}
FileList.replaceCanceled = true;
FileList.replaceOldName = null;
FileList.replaceNewName = null;
FileList.lastAction = null;
}});
}, true);
}
},
do_delete:function(files){
// Finish any existing actions
if (FileList.lastAction || !FileList.useUndo) {
if(!FileList.deleteFiles) {
FileList.prepareDeletion(files);
}
FileList.lastAction();
return;
}
FileList.prepareDeletion(files);
$('#notification').html(t('files', 'deleted')+' '+files+'<span class="undo">'+t('files', 'undo')+'</span>');
$('#notification').fadeIn();
},
finishDelete:function(ready,sync){
if(!FileList.deleteCanceled && FileList.deleteFiles){
var fileNames=FileList.deleteFiles.join(';');
$.ajax({
url: OC.filePath('files', 'ajax', 'delete.php'),
async:!sync,
data: {dir:$('#dir').val(),files:fileNames},
complete: function(data){
boolOperationFinished(data, function(){
$('#notification').fadeOut();
$.each(FileList.deleteFiles,function(index,file){
FileList.remove(file);
});
FileList.deleteCanceled=true;
FileList.deleteFiles=null;
FileList.lastAction = null;
if(ready){
ready();
}
});
}
});
}
},
prepareDeletion:function(files){
if(files.substr){
files=[files];
}
$.each(files,function(index,file){
var files = $('tr').filterAttr('data-file',file);
files.hide();
files.find('input[type="checkbox"]').removeAttr('checked');
files.removeClass('selected');
});
procesSelection();
FileList.deleteCanceled=false;
FileList.deleteFiles=files;
FileList.lastAction = function() {
FileList.finishDelete(null, true);
};
}
}
$(document).ready(function(){
$('#notification').hide();
$('#notification .undo').live('click', function(){
if (FileList.deleteFiles) {
$.each(FileList.deleteFiles,function(index,file){
$('tr').filterAttr('data-file',file).show();
});
FileList.deleteCanceled=true;
FileList.deleteFiles=null;
} else if (FileList.replaceOldName && FileList.replaceNewName) {
$('tr').filterAttr('data-file', FileList.replaceOldName).show();
FileList.replaceCanceled = true;
FileList.replaceOldName = null;
FileList.replaceNewName = null;
}
$('#notification').fadeOut();
});
$('#notification .replace').live('click', function() {
$('#notification').fadeOut('400', function() {
FileList.replace($('#notification').data('oldName'), $('#notification').data('newName'));
});
});
$('#notification .cancel').live('click', function() {
$('#notification').fadeOut();
});
FileList.useUndo=('onbeforeunload' in window)
$(window).bind('beforeunload', function (){
if (FileList.lastAction) {
FileList.lastAction();
}
});
});
| apps/files/js/filelist.js | FileList={
useUndo:true,
update:function(fileListHtml) {
$('#fileList').empty().html(fileListHtml);
},
addFile:function(name,size,lastModified,loading){
var img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file.png');
var html='<tr data-type="file" data-size="'+size+'">';
if(name.indexOf('.')!=-1){
var basename=name.substr(0,name.lastIndexOf('.'));
var extension=name.substr(name.lastIndexOf('.'));
}else{
var basename=name;
var extension=false;
}
html+='<td class="filename" style="background-image:url('+img+')"><input type="checkbox" />';
html+='<a class="name" href="download.php?file='+$('#dir').val().replace(/</, '<').replace(/>/, '>')+'/'+name+'"><span class="nametext">'+basename
if(extension){
html+='<span class="extension">'+extension+'</span>';
}
html+='</span></a></td>';
if(size!='Pending'){
simpleSize=simpleFileSize(size);
}else{
simpleSize='Pending';
}
sizeColor = Math.round(200-size/(1024*1024)*2);
lastModifiedTime=Math.round(lastModified.getTime() / 1000);
modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
html+='<td class="filesize" title="'+humanFileSize(size)+'" style="color:rgb('+sizeColor+','+sizeColor+','+sizeColor+')">'+simpleSize+'</td>';
html+='<td class="date"><span class="modified" title="'+formatDate(lastModified)+'" style="color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')">'+relative_modified_date(lastModified.getTime() / 1000)+'</span></td>';
html+='</tr>';
FileList.insertElement(name,'file',$(html).attr('data-file',name));
if(loading){
$('tr').filterAttr('data-file',name).data('loading',true);
}else{
$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions);
}
},
addDir:function(name,size,lastModified){
html = $('<tr></tr>').attr({ "data-type": "dir", "data-size": size, "data-file": name});
td = $('<td></td>').attr({"class": "filename", "style": 'background-image:url('+OC.imagePath('core', 'filetypes/folder.png')+')' });
td.append('<input type="checkbox" />');
var link_elem = $('<a></a>').attr({ "class": "name", "href": OC.linkTo('files', 'index.php')+"&dir="+ encodeURIComponent($('#dir').val()+'/'+name).replace(/%2F/g, '/') });
link_elem.append($('<span></span>').addClass('nametext').text(name));
link_elem.append($('<span></span>').attr({'class': 'uploadtext', 'currentUploads': 0}));
td.append(link_elem);
html.append(td);
if(size!='Pending'){
simpleSize=simpleFileSize(size);
}else{
simpleSize='Pending';
}
sizeColor = Math.round(200-Math.pow((size/(1024*1024)),2));
lastModifiedTime=Math.round(lastModified.getTime() / 1000);
modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*5);
td = $('<td></td>').attr({ "class": "filesize", "title": humanFileSize(size), "style": 'color:rgb('+sizeColor+','+sizeColor+','+sizeColor+')'}).text(simpleSize);
html.append(td);
td = $('<td></td>').attr({ "class": "date" });
td.append($('<span></span>').attr({ "class": "modified", "title": formatDate(lastModified), "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')' }).text( relative_modified_date(lastModified.getTime() / 1000) ));
html.append(td);
FileList.insertElement(name,'dir',html);
$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions);
$('tr').filterAttr('data-file',name).find('td.filename').droppable(folderDropOptions);
},
refresh:function(data) {
result = jQuery.parseJSON(data.responseText);
if(typeof(result.data.breadcrumb) != 'undefined'){
updateBreadcrumb(result.data.breadcrumb);
}
FileList.update(result.data.files);
resetFileActionPanel();
},
remove:function(name){
$('tr').filterAttr('data-file',name).find('td.filename').draggable('destroy');
$('tr').filterAttr('data-file',name).remove();
if($('tr[data-file]').length==0){
$('#emptyfolder').show();
$('.file_upload_filename').addClass('highlight');
}
},
insertElement:function(name,type,element){
//find the correct spot to insert the file or folder
var fileElements=$('tr[data-file][data-type="'+type+'"]');
var pos;
if(name.localeCompare($(fileElements[0]).attr('data-file'))<0){
pos=-1;
}else if(name.localeCompare($(fileElements[fileElements.length-1]).attr('data-file'))>0){
pos=fileElements.length-1;
}else{
for(var pos=0;pos<fileElements.length-1;pos++){
if(name.localeCompare($(fileElements[pos]).attr('data-file'))>0 && name.localeCompare($(fileElements[pos+1]).attr('data-file'))<0){
break;
}
}
}
if(fileElements.length){
if(pos==-1){
$(fileElements[0]).before(element);
}else{
$(fileElements[pos]).after(element);
}
}else if(type=='dir' && $('tr[data-file]').length>0){
$('tr[data-file]').first().before(element);
}else{
$('#fileList').append(element);
}
$('#emptyfolder').hide();
$('.file_upload_filename').removeClass('highlight');
},
loadingDone:function(name){
var tr=$('tr').filterAttr('data-file',name);
tr.data('loading',false);
var mime=tr.data('mime');
tr.attr('data-mime',mime);
getMimeIcon(mime,function(path){
tr.find('td.filename').attr('style','background-image:url('+path+')');
});
tr.find('td.filename').draggable(dragOptions);
},
isLoading:function(name){
return $('tr').filterAttr('data-file',name).data('loading');
},
rename:function(name){
var tr=$('tr').filterAttr('data-file',name);
tr.data('renaming',true);
var td=tr.children('td.filename');
var input=$('<input class="filename"></input>').val(name);
var form=$('<form></form>')
form.append(input);
td.children('a.name').text('');
td.children('a.name').append(form)
input.focus();
form.submit(function(event){
event.stopPropagation();
event.preventDefault();
var newname=input.val();
if (newname != name) {
if ($('tr').filterAttr('data-file', newname).length > 0) {
$('#notification').html(newname+' '+t('files', 'already exists')+'<span class="replace">'+t('files', 'replace')+'</span><span class="cancel">'+t('files', 'cancel')+'</span>');
$('#notification').data('oldName', name);
$('#notification').data('newName', newname);
$('#notification').fadeIn();
newname = name;
} else {
$.get(OC.filePath('files','ajax','rename.php'), { dir : $('#dir').val(), newname: newname, file: name },function(result) {
if (!result || result.status == 'error') {
OC.dialogs.alert(result.data.message, 'Error moving file');
newname = name;
}
});
}
}
tr.attr('data-file', newname);
var path = td.children('a.name').attr('href');
td.children('a.name').attr('href', path.replace(encodeURIComponent(name), encodeURIComponent(newname)));
if (newname.indexOf('.') > 0) {
var basename=newname.substr(0,newname.lastIndexOf('.'));
} else {
var basename=newname;
}
td.children('a.name').empty();
var span=$('<span class="nametext"></span>');
span.text(basename);
td.children('a.name').append(span);
if (newname.indexOf('.') > 0) {
span.append($('<span class="extension">'+newname.substr(newname.lastIndexOf('.'))+'</span>'));
}
tr.data('renaming',false);
return false;
});
input.click(function(event){
event.stopPropagation();
event.preventDefault();
});
input.blur(function(){
form.trigger('submit');
});
},
replace:function(oldName, newName) {
// Finish any existing actions
if (FileList.lastAction || !FileList.useUndo) {
FileList.lastAction();
}
var tr = $('tr').filterAttr('data-file', oldName);
tr.hide();
FileList.replaceCanceled = false;
FileList.replaceOldName = oldName;
FileList.replaceNewName = newName;
FileList.lastAction = function() {
FileList.finishReplace();
};
$('#notification').html(t('files', 'replaced')+' '+newName+' '+t('files', 'with')+' '+oldName+'<span class="undo">'+t('files', 'undo')+'</span>');
$('#notification').fadeIn();
},
finishReplace:function() {
if (!FileList.replaceCanceled && FileList.replaceOldName && FileList.replaceNewName) {
// Delete the file being replaced and rename the replacement
FileList.deleteCanceled = false;
FileList.deleteFiles = [FileList.replaceNewName];
FileList.finishDelete(function() {
$.ajax({url: OC.filePath('files', 'ajax', 'rename.php'), async: false, data: { dir: $('#dir').val(), newname: FileList.replaceNewName, file: FileList.replaceOldName }, success: function(result) {
if (result && result.status == 'success') {
var tr = $('tr').filterAttr('data-file', FileList.replaceOldName);
tr.attr('data-file', FileList.replaceNewName);
var td = tr.children('td.filename');
td.children('a.name .span').text(FileList.replaceNewName);
var path = td.children('a.name').attr('href');
td.children('a.name').attr('href', path.replace(encodeURIComponent(FileList.replaceOldName), encodeURIComponent(FileList.replaceNewName)));
if (FileList.replaceNewName.indexOf('.') > 0) {
var basename = FileList.replaceNewName.substr(0, FileList.replaceNewName.lastIndexOf('.'));
} else {
var basename = FileList.replaceNewName;
}
td.children('a.name').empty();
var span = $('<span class="nametext"></span>');
span.text(basename);
td.children('a.name').append(span);
if (FileList.replaceNewName.indexOf('.') > 0) {
span.append($('<span class="extension">'+FileList.replaceNewName.substr(FileList.replaceNewName.lastIndexOf('.'))+'</span>'));
}
tr.show();
} else {
OC.dialogs.alert(result.data.message, 'Error moving file');
}
FileList.replaceCanceled = true;
FileList.replaceOldName = null;
FileList.replaceNewName = null;
FileList.lastAction = null;
}});
}, true);
}
},
do_delete:function(files){
// Finish any existing actions
if (FileList.lastAction || !FileList.useUndo) {
FileList.lastAction();
}
if(files.substr){
files=[files];
}
$.each(files,function(index,file){
var files = $('tr').filterAttr('data-file',file);
files.hide();
files.find('input[type="checkbox"]').removeAttr('checked');
files.removeClass('selected');
});
procesSelection();
FileList.deleteCanceled=false;
FileList.deleteFiles=files;
FileList.lastAction = function() {
FileList.finishDelete(null, true);
};
$('#notification').html(t('files', 'deleted')+' '+files+'<span class="undo">'+t('files', 'undo')+'</span>');
$('#notification').fadeIn();
},
finishDelete:function(ready,sync){
if(!FileList.deleteCanceled && FileList.deleteFiles){
var fileNames=FileList.deleteFiles.join(';');
$.ajax({
url: OC.filePath('files', 'ajax', 'delete.php'),
async:!sync,
data: {dir:$('#dir').val(),files:fileNames},
complete: function(data){
boolOperationFinished(data, function(){
$('#notification').fadeOut();
$.each(FileList.deleteFiles,function(index,file){
FileList.remove(file);
});
FileList.deleteCanceled=true;
FileList.deleteFiles=null;
FileList.lastAction = null;
if(ready){
ready();
}
});
}
});
}
}
}
$(document).ready(function(){
$('#notification').hide();
$('#notification .undo').live('click', function(){
if (FileList.deleteFiles) {
$.each(FileList.deleteFiles,function(index,file){
$('tr').filterAttr('data-file',file).show();
});
FileList.deleteCanceled=true;
FileList.deleteFiles=null;
} else if (FileList.replaceOldName && FileList.replaceNewName) {
$('tr').filterAttr('data-file', FileList.replaceOldName).show();
FileList.replaceCanceled = true;
FileList.replaceOldName = null;
FileList.replaceNewName = null;
}
$('#notification').fadeOut();
});
$('#notification .replace').live('click', function() {
$('#notification').fadeOut('400', function() {
FileList.replace($('#notification').data('oldName'), $('#notification').data('newName'));
});
});
$('#notification .cancel').live('click', function() {
$('#notification').fadeOut();
});
FileList.useUndo=('onbeforeunload' in window)
$(window).bind('beforeunload', function (){
if (FileList.lastAction) {
FileList.lastAction();
}
});
});
| Fix deletion for browser that do not support onBeforeUnload, fixes oc-1534.
| apps/files/js/filelist.js | Fix deletion for browser that do not support onBeforeUnload, fixes oc-1534. | <ide><path>pps/files/js/filelist.js
<ide> }
<ide> });
<ide> }
<del>
<add>
<ide> }
<ide> tr.attr('data-file', newname);
<ide> var path = td.children('a.name').attr('href');
<ide> FileList.replaceCanceled = false;
<ide> FileList.replaceOldName = oldName;
<ide> FileList.replaceNewName = newName;
<del> FileList.lastAction = function() {
<add> FileList.lastAction = function() {
<ide> FileList.finishReplace();
<ide> };
<ide> $('#notification').html(t('files', 'replaced')+' '+newName+' '+t('files', 'with')+' '+oldName+'<span class="undo">'+t('files', 'undo')+'</span>');
<ide> do_delete:function(files){
<ide> // Finish any existing actions
<ide> if (FileList.lastAction || !FileList.useUndo) {
<add> if(!FileList.deleteFiles) {
<add> FileList.prepareDeletion(files);
<add> }
<ide> FileList.lastAction();
<del> }
<del> if(files.substr){
<del> files=[files];
<del> }
<del> $.each(files,function(index,file){
<del> var files = $('tr').filterAttr('data-file',file);
<del> files.hide();
<del> files.find('input[type="checkbox"]').removeAttr('checked');
<del> files.removeClass('selected');
<del> });
<del> procesSelection();
<del> FileList.deleteCanceled=false;
<del> FileList.deleteFiles=files;
<del> FileList.lastAction = function() {
<del> FileList.finishDelete(null, true);
<del> };
<add> return;
<add> }
<add> FileList.prepareDeletion(files);
<ide> $('#notification').html(t('files', 'deleted')+' '+files+'<span class="undo">'+t('files', 'undo')+'</span>');
<ide> $('#notification').fadeIn();
<ide> },
<ide> }
<ide> });
<ide> }
<add> },
<add> prepareDeletion:function(files){
<add> if(files.substr){
<add> files=[files];
<add> }
<add> $.each(files,function(index,file){
<add> var files = $('tr').filterAttr('data-file',file);
<add> files.hide();
<add> files.find('input[type="checkbox"]').removeAttr('checked');
<add> files.removeClass('selected');
<add> });
<add> procesSelection();
<add> FileList.deleteCanceled=false;
<add> FileList.deleteFiles=files;
<add> FileList.lastAction = function() {
<add> FileList.finishDelete(null, true);
<add> };
<ide> }
<ide> }
<ide> |
|
Java | bsd-2-clause | 7936497ec994d4136a8da1ffd281c9c743964edf | 0 | TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing;
import imagej.ImageJ;
import imagej.core.plugins.overlay.SelectedManagerOverlayProperties;
import imagej.data.ChannelCollection;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.data.ImageGrabber;
import imagej.data.display.DataView;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.display.OverlayInfo;
import imagej.data.display.OverlayInfoList;
import imagej.data.display.OverlayService;
import imagej.data.display.OverlayView;
import imagej.data.display.event.DataViewSelectionEvent;
import imagej.data.event.OverlayCreatedEvent;
import imagej.data.event.OverlayDeletedEvent;
import imagej.data.event.OverlayRestructuredEvent;
import imagej.data.event.OverlayUpdatedEvent;
import imagej.data.overlay.Overlay;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.DisplayService;
import imagej.ext.plugin.PluginService;
import imagej.log.LogService;
import imagej.options.OptionsService;
import imagej.options.plugins.OptionsChannels;
import imagej.platform.PlatformService;
import imagej.util.Prefs;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
// TODO
//
// - implement methods that actually do stuff
// - since it knows its a Swing UI it uses Swing UI features. Ideally we should
// make OverlayManager a Display<Overlay> and work as much as possible in
// an agnostic fashion. Thus no swing style listeners but instead IJ2
// listeners. And rather than swing input dialogs we should make IJ2 input
// dialogs.
/**
* Overlay Manager Swing UI
*
* @author Barry DeZonia
* @author Adam Fraser
*/
public class SwingOverlayManager
extends JFrame
implements ActionListener, ItemListener
{
// -- constants --
//private static final long serialVersionUID = -6498169032123522303L;
// no longer supported
//private static final String ACTION_ADD = "add";
private static final String ACTION_ADD_PARTICLES = "add particles";
private static final String ACTION_AND = "and";
private static final String ACTION_DELETE = "delete";
private static final String ACTION_DESELECT = "deselect";
private static final String ACTION_DRAW = "draw";
private static final String ACTION_FILL = "fill";
private static final String ACTION_FLATTEN = "flatten";
private static final String ACTION_HELP = "help";
private static final String ACTION_MEASURE = "measure";
private static final String ACTION_MULTI_MEASURE = "multi measure";
private static final String ACTION_MULTI_PLOT = "multi plot";
private static final String ACTION_OPEN = "open";
private static final String ACTION_OPTIONS = "options";
private static final String ACTION_OR = "or";
private static final String ACTION_PROPERTIES = "properties";
private static final String ACTION_REMOVE_SLICE_INFO = "remove slice info";
private static final String ACTION_RENAME = "rename";
private static final String ACTION_SAVE = "save";
private static final String ACTION_SORT = "sort";
private static final String ACTION_SPECIFY = "specify";
private static final String ACTION_SPLIT = "split";
// no longer supported
//private static final String ACTION_UPDATE = "update";
private static final String ACTION_XOR = "xor";
private static final String LAST_X = "lastXLocation";
private static final String LAST_Y = "lastYLocation";
// -- instance variables --
/** Maintains the list of event subscribers, to avoid garbage collection. */
@SuppressWarnings("unused")
private final List<EventSubscriber<?>> subscribers;
private final ImageJ context;
private final JList jlist;
private boolean selecting = false; // flag to prevent event feedback loops
private JPopupMenu popupMenu = null;
private final JCheckBox showAllCheckBox;
private final JCheckBox editModeCheckBox;
private boolean shiftDown = false;
private boolean altDown = false;
private final OverlayService ovrSrv;
// -- constructor --
/**
* Creates a JList to list the overlays.
*/
public SwingOverlayManager(final ImageJ context) {
this.context = context;
this.ovrSrv = context.getService(OverlayService.class);
jlist = new JList(new OverlayListModel(ovrSrv.getOverlayInfo()));
//jlist.setCellRenderer(new OverlayRenderer());
final JScrollPane listScroller = new JScrollPane(jlist);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
final JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
listPanel.add(listScroller);
listPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
final JPanel buttonPane = new JPanel();
buttonPane.setLayout(new GridLayout(9,1,5,0));
// NO LONGER SUPPORTING
//buttonPane.add(getAddButton());
//buttonPane.add(getUpdateButton());
buttonPane.add(getDeleteButton());
buttonPane.add(getRenameButton());
buttonPane.add(getMeasureButton());
buttonPane.add(getDeselectButton());
buttonPane.add(getPropertiesButton());
buttonPane.add(getFlattenButton());
buttonPane.add(getFillButton());
buttonPane.add(getDrawButton());
buttonPane.add(getMoreButton());
final JPanel boolPane = new JPanel();
boolPane.setLayout(new BoxLayout(boolPane, BoxLayout.Y_AXIS));
showAllCheckBox = new JCheckBox("Show All",false);
editModeCheckBox = new JCheckBox("Edit Mode",false);
boolPane.add(showAllCheckBox);
boolPane.add(editModeCheckBox);
showAllCheckBox.addItemListener(this);
editModeCheckBox.addItemListener(this);
final JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BorderLayout());
controlPanel.add(buttonPane,BorderLayout.CENTER);
controlPanel.add(boolPane,BorderLayout.SOUTH);
final Container cp = this.getContentPane();
cp.add(listPanel, BorderLayout.CENTER);
cp.add(controlPanel, BorderLayout.EAST);
setTitle("Overlay Manager");
setupListSelectionListener();
setupCloseListener();
setupKeyListener();
restoreLocation();
pack();
final EventService eventService = context.getService(EventService.class);
subscribers = eventService.subscribe(this);
/* NOTE BDZ removed 6-11-12. There should be a default menu bar attached
* to this frame now.
*
// FIXME - temp hack - made this class (which is not a display) make sure
// menu bar available when it is running. Ugly cast in place to create the
// menu bar. A better approach would be to make a new event tied to a menu
// bar listener of some sort. This code could emit that "need a menu bar"
// event here. Filing as ticket.
final UIService uiService = context.getService(UIService.class);
((AbstractSwingUI)uiService.getUI()).createMenuBar(this, false);
*/
populateOverlayList();
}
// -- public interface --
@Override
public void actionPerformed(final ActionEvent e) {
final String command = e.getActionCommand();
if (command == null) return;
/* no longer supported
if (command.equals(ACTION_ADD))
add();
*/
if (command.equals(ACTION_ADD_PARTICLES))
addParticles();
else if (command.equals(ACTION_AND))
and();
else if (command.equals(ACTION_DELETE))
delete();
else if (command.equals(ACTION_DESELECT))
deselect();
else if (command.equals(ACTION_DRAW))
draw();
else if (command.equals(ACTION_FILL))
fill();
else if (command.equals(ACTION_FLATTEN))
flatten();
else if (command.equals(ACTION_HELP))
help();
else if (command.equals(ACTION_MEASURE))
measure();
else if (command.equals(ACTION_MULTI_MEASURE))
multiMeasure();
else if (command.equals(ACTION_MULTI_PLOT))
multiPlot();
else if (command.equals(ACTION_OPEN))
open();
else if (command.equals(ACTION_OPTIONS))
options();
else if (command.equals(ACTION_OR))
or();
else if (command.equals(ACTION_PROPERTIES))
properties();
else if (command.equals(ACTION_REMOVE_SLICE_INFO))
removeSliceInfo();
else if (command.equals(ACTION_RENAME))
rename();
else if (command.equals(ACTION_SAVE))
save();
else if (command.equals(ACTION_SORT))
sort();
else if (command.equals(ACTION_SPECIFY))
specify();
else if (command.equals(ACTION_SPLIT))
split();
/*
else if (command.equals(ACTION_UPDATE))
update();
*/
else if (command.equals(ACTION_XOR))
xor();
}
// -- private helpers for overlay list maintenance --
private class OverlayListModel extends AbstractListModel {
//private static final long serialVersionUID = 7941252533859436640L;
private OverlayInfoList overlayInfoList;
public OverlayListModel(OverlayInfoList list) {
overlayInfoList = list;
}
@Override
public Object getElementAt(final int index) {
return overlayInfoList.getOverlayInfo(index);
}
@Override
public int getSize() {
return overlayInfoList.getOverlayInfoCount();
}
}
/*
*/
private void populateOverlayList() {
// Populate the list with all overlays
for (final Overlay overlay : ovrSrv.getOverlays()) {
boolean found = false;
int totOverlays = ovrSrv.getOverlayInfo().getOverlayInfoCount();
for (int i = 0; i < totOverlays; i++) {
OverlayInfo info = ovrSrv.getOverlayInfo().getOverlayInfo(i);
if (overlay == info.getOverlay()) {
found = true;
break;
}
}
if (!found) {
OverlayInfo info = new OverlayInfo(overlay);
ovrSrv.getOverlayInfo().addOverlayInfo(info);
}
}
jlist.updateUI();
}
/*
private class OverlayRenderer extends DefaultListCellRenderer {
//private static final long serialVersionUID = 2468086636364454253L;
private final Hashtable<Overlay, ImageIcon> iconTable =
new Hashtable<Overlay, ImageIcon>();
@Override
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean hasFocus)
{
final JLabel label =
(JLabel) super.getListCellRendererComponent(list, value, index,
isSelected, hasFocus);
if (value instanceof Overlay) {
final Overlay overlay = (Overlay) value;
// TODO: create overlay thumbnail from overlay
final ImageIcon icon = iconTable.get(overlay);
// if (icon == null) {
// icon = new ImageIcon(...);
// iconTable.put(overlay, ImageIcon);
// }
label.setIcon(icon);
}
else {
// Clear old icon; needed in 1st release of JDK 1.2
label.setIcon(null);
}
return label;
}
}
*/
// -- event handlers --
@EventHandler
protected void onEvent(final OverlayCreatedEvent event) {
//System.out.println("\tCREATED: " + event.toString());
ovrSrv.getOverlayInfo().addOverlay(event.getObject());
jlist.updateUI();
}
@EventHandler
protected void onEvent(final OverlayDeletedEvent event) {
//System.out.println("\tDELETED: " + event.toString());
Overlay overlay = event.getObject();
ovrSrv.getOverlayInfo().deleteOverlay(overlay);
int[] newSelectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(newSelectedIndices);
jlist.updateUI();
}
/*
// Update when a display is activated.
@EventHandler
protected void onEvent(
@SuppressWarnings("unused") final DisplayActivatedEvent event)
{
jlist.updateUI();
}
*/
@EventHandler
protected void onEvent(final DataViewSelectionEvent event) {
if (selecting) return;
selecting = true;
// Select or deselect the corresponding overlay in the list
final Overlay overlay = (Overlay) event.getView().getData();
final int overlayIndex = ovrSrv.getOverlayInfo().findIndex(overlay);
final OverlayInfo overlayInfo = ovrSrv.getOverlayInfo().getOverlayInfo(overlayIndex);
overlayInfo.setSelected(event.isSelected());
/* old way
if (event.isSelected()) {
final int[] current_sel = jlist.getSelectedIndices();
jlist.setSelectedValue(overlayInfo, true);
final int[] new_sel = jlist.getSelectedIndices();
final int[] sel =
Arrays.copyOf(current_sel, current_sel.length + new_sel.length);
System.arraycopy(new_sel, 0, sel, current_sel.length, new_sel.length);
jlist.setSelectedIndices(sel);
}
else {
for (final int i : jlist.getSelectedIndices()) {
if (jlist.getModel().getElementAt(i) == overlayInfo) {
jlist.removeSelectionInterval(i, i);
}
}
}
*/
int[] selections = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(selections);
selecting = false;
}
/*
// TODO - this may not be best way to do this
// Its here to allow acceleration without ALT/OPTION key
// Maybe make buttons listen for actions
@EventHandler
protected void onKeyPressedEvent(KyPressedEvent ev) {
System.out.println("key press registered to display "+ev.getDisplay());
altDown = ev.getModifiers().isAltDown() || ev.getModifiers().isAltGrDown();
shiftDown = ev.getModifiers().isShiftDown();
KeyCode key = ev.getCode();
if (key == KeyCode.T) add();
if (key == KeyCode.F) flatten();
if (key == KeyCode.DELETE) delete();
}
*/
@SuppressWarnings("unused")
@EventHandler
protected void onEvent(OverlayRestructuredEvent event) {
//System.out.println("restructured");
jlist.updateUI();
}
@SuppressWarnings("unused")
@EventHandler
protected void onEvent(OverlayUpdatedEvent event) {
//System.out.println("updated");
jlist.updateUI();
}
// -- private helpers that implement overlay interaction commands --
/* no longer supported
private void add() {
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay activeDisplay = ids.getActiveImageDisplay();
if (activeDisplay == null) return;
final List<DataView> views = activeDisplay;
boolean additions = false;
for (DataView view : views) {
if (view.isSelected() && (view instanceof OverlayView))
additions |= infoList.addOverlay((Overlay)view.getData());
}
if (additions)
jlist.updateUI();
}
*/
private void addParticles() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void and() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void delete() {
if (ovrSrv.getOverlayInfo().getOverlayInfoCount() == 0) return;
List<Overlay> overlaysToDelete = new LinkedList<Overlay>();
final int[] selectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
if (selectedIndices.length == 0) {
final int result =
JOptionPane.showConfirmDialog(
this, "Delete all overlays?", "Delete All", JOptionPane.YES_NO_OPTION);
if (result != JOptionPane.YES_OPTION) return;
for (int i = 0; i < ovrSrv.getOverlayInfo().getOverlayInfoCount(); i++) {
overlaysToDelete.add(ovrSrv.getOverlayInfo().getOverlayInfo(i).getOverlay());
}
}
else {
for (int i = 0; i < selectedIndices.length; i++) {
int index = selectedIndices[i];
overlaysToDelete.add(ovrSrv.getOverlayInfo().getOverlayInfo(index).getOverlay());
}
}
for (Overlay overlay : overlaysToDelete) {
// NB - removeOverlay() can indirectly change our infoList contents.
// Thus we first collect overlays from the infoList and then delete
// them all afterwards to avoid interactions.
ovrSrv.removeOverlay(overlay);
}
}
private void deselect() {
ovrSrv.getOverlayInfo().deselectAll();
jlist.clearSelection();
}
private void draw() {
OverlayService os = context.getService(OverlayService.class);
ChannelCollection channels = getChannels();
List<Overlay> selected = ovrSrv.getOverlayInfo().selectedOverlays();
for (Overlay o : selected) {
ImageDisplay disp = os.getFirstDisplay(o);
os.drawOverlay(o, disp, channels);
}
}
private void fill() {
OverlayService os = context.getService(OverlayService.class);
ChannelCollection channels = getChannels();
List<Overlay> selected = ovrSrv.getOverlayInfo().selectedOverlays();
for (Overlay o : selected) {
ImageDisplay disp = os.getFirstDisplay(o);
os.fillOverlay(o, disp, channels);
}
}
/* FIXME TODO notes
* I'm pretty sure this just snapshots the current view and returns a new
* Dataset/Img that is one dimensional, usually rgb, and shows drawn rois.
* If show all is true it draws all rois, else it draws curr roi. Note that
* we can get rid of show all I think because we always show all. Is that a
* problem? Edit mode renders differently. This might affect OverlayService
* for drawOverlay() and fillOverlay(). Do we need a way to show single
* overlays now? Probably. More hints for OverlayService I suppose. Anyhow
* we grab the current view as a merged color dataset using an ImageGrabber.
* Right now this implementation does not show the ROI outline. Thats all the
* special case code the ROI Mgr flatten does compared to the menu command
* flatten. We need a way to tell the OverlayService to draw an Overlay in a
* given Dataset. But we want to draw using fg/bg sometimes and using default
* drawing capabilities sometimes (like JHotDraw's rendering).
*/
private void flatten() {
/*
List<Overlay> selOverlays = infoList.selectedOverlays();
if (selOverlays.size() == 0) {
JOptionPane.showMessageDialog(this, "At least one overlay must be selected");
return;
}
*/
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay imageDisplay = ids.getActiveImageDisplay();
if (imageDisplay == null) return;
final DatasetView view = ids.getActiveDatasetView(imageDisplay);
if (view == null) return;
DatasetService dss = context.getService(DatasetService.class);
String datasetName = imageDisplay.getName() + " - flattened";
Dataset dataset = new ImageGrabber(dss).grab(view, datasetName);
DisplayService ds = context.getService(DisplayService.class);
ds.createDisplay(dataset.getName(), dataset);
// TODO - This currently does not show the ROI outline
}
private void help() {
LogService log = context.getService(LogService.class);
log.warn("TODO in SwingOverlayManager::help() - using old IJ1 URL for this command");
final PlatformService ps = context.getService(PlatformService.class);
try {
final URL url =
new URL("http://imagej.nih.gov/ij/docs/menus/analyze.html#manager");
ps.open(url);
} catch (IOException e) {
// do nothing
}
}
private void measure() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void multiMeasure() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void multiPlot() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void open() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void options() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void or() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void properties() {
int[] selected = ovrSrv.getOverlayInfo().selectedIndices();
if (selected.length == 0) {
JOptionPane.showMessageDialog(this, "This command requires one or more selections");
return;
}
// else one or more selections exist
runPropertiesPlugin();
}
private void removeSliceInfo() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void rename() {
final int[] selectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
if (selectedIndices.length < 1) {
JOptionPane.showMessageDialog(this, "Must select an overlay to rename");
return;
}
if (selectedIndices.length > 1) {
JOptionPane.showMessageDialog(this, "Cannot rename multiple overlays simultaneously");
return;
}
final OverlayInfo info = ovrSrv.getOverlayInfo().getOverlayInfo(selectedIndices[0]);
if (info == null) return;
// TODO - UI agnostic way here
final String name = JOptionPane.showInputDialog(this, "Enter new name for overlay");
if ((name == null) || (name.length() == 0))
info.getOverlay().setName(null);
else
info.getOverlay().setName(name);
jlist.updateUI();
}
private void save() {
JOptionPane.showMessageDialog(this, "unimplemented");
/*
final int[] selectedIndices = jlist.getSelectedIndices();
// nothing selected
if (selectedIndices.length == 0) {
JOptionPane.showMessageDialog(this, "Cannot save - one or more overlays must be selected first");
return;
}
final JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save Overlay to file ...");
chooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter1, filter2;
filter1 = new FileNameExtensionFilter("ImageJ overlay containers (*.zip)", "zip");
chooser.addChoosableFileFilter(filter1);
filter2 = new FileNameExtensionFilter("ImageJ overlay files (*.ovl)", "ovl");
chooser.addChoosableFileFilter(filter2);
chooser.setFileFilter(filter2);
int result = chooser.showSaveDialog(this);
if (result != JFileChooser.APPROVE_OPTION) return;
String basename = chooser.getSelectedFile().getAbsolutePath();
if (basename.toLowerCase().endsWith(".ovl") ||
basename.toLowerCase().endsWith(".zip")) {
basename = basename.substring(0,basename.length()-4);
}
// one roi selected
if (selectedIndices.length == 1) {
// save overlay in its own user named .ovl file
String filename = basename + ".ovl";
final OverlayInfo info = (OverlayInfo) jlist.getSelectedValue();
//info.overlay.save(filename);
}
else { // more than one roi selected
// save each overlay in its own .ovl file in a user named .zip container
String filename = basename + ".zip";
JOptionPane.showMessageDialog(this, "save multiple overlays to zip is unimplemented");
}
*/
}
private void sort() {
ovrSrv.getOverlayInfo().sort();
int[] newSelections = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(newSelections);
jlist.updateUI();
}
private void specify() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void split() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
/*
* old functionality : now that all overlays always tracked this no longer
* makes sense
*
// replace OverlayInfoList's currently selected info with the currently
// selected roi
private void update() {
final int[] selectedIndices = infoList.selectedIndices();
if (selectedIndices.length != 1) {
JOptionPane.showMessageDialog(this,
"Exactly one item must be selected");
return;
}
final Overlay overlay = getActiveOverlay();
if (overlay == null) {
JOptionPane.showMessageDialog(this,
"An overlay must be selected in the current view");
return;
}
final int index = infoList.findIndex(overlay);
if (index != -1) {
// already in list
if (index != selectedIndices[0])
JOptionPane.showMessageDialog(this,
"Selected overlay is already tracked by the overlay manager");
return;
}
infoList.replaceOverlay(selectedIndices[0], overlay);
jlist.updateUI();
}
*/
private void xor() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
// -- private helpers for hotkey handling --
private void setupKeyListener() {
//KeyListener listener = new AWTKeyEventDispatcher(fakeDisplay, eventService);
final KeyListener listener = new KeyListener() {
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
altDown = e.isAltDown() || e.isAltGraphDown();
shiftDown = e.isShiftDown();
/* no longer supported
if (e.getKeyCode() == KeyEvent.VK_T) add();
*/
if (e.getKeyCode() == KeyEvent.VK_F) flatten();
if (e.getKeyCode() == KeyEvent.VK_DELETE) delete();
}
@Override
@SuppressWarnings("synthetic-access")
public void keyReleased(KeyEvent e) {
altDown = e.isAltDown() || e.isAltGraphDown();
shiftDown = e.isShiftDown();
}
@Override
public void keyTyped(KeyEvent e) { /* do nothing */ }
};
final Stack<Component> stack = new Stack<Component>();
stack.push(this);
while (!stack.empty()) {
final Component component = stack.pop();
component.addKeyListener(listener);
if (component instanceof Container) {
final Container container = (Container) component;
for (Component c : container.getComponents())
stack.push(c);
}
}
}
// -- private helpers for frame location --
/** Persists the application frame's current location. */
private void saveLocation() {
Prefs.put(getClass(), LAST_X, getLocation().x);
Prefs.put(getClass(), LAST_Y, getLocation().y);
}
/** Restores the application frame's current location. */
private void restoreLocation() {
final int lastX = Prefs.getInt(getClass(), LAST_X, 0);
final int lastY = Prefs.getInt(getClass(), LAST_Y, 0);
setLocation(lastX, lastY);
}
private void setupCloseListener() {
addWindowListener(new WindowAdapter() {
@Override
@SuppressWarnings("synthetic-access")
public void windowClosing(WindowEvent e) {
// Remember screen location of window for next time
saveLocation();
}
});
}
// -- private helpers for list selection event listening --
private void setupListSelectionListener() {
final ListSelectionListener
listSelectionListener = new ListSelectionListener() {
@Override
@SuppressWarnings("synthetic-access")
public void valueChanged(final ListSelectionEvent listSelectionEvent) {
if (selecting) return;
selecting = true;
final ImageDisplayService imageDisplayService =
context.getService(ImageDisplayService.class);
final ImageDisplay display =
imageDisplayService.getActiveImageDisplay();
if (display == null) return;
final JList list = (JList) listSelectionEvent.getSource();
final Object[] selectionValues = list.getSelectedValues();
ovrSrv.getOverlayInfo().deselectAll();
for (final Object overlayInfoObj : selectionValues) {
final OverlayInfo overlayInfo = (OverlayInfo) overlayInfoObj;
overlayInfo.setSelected(true);
}
for (final DataView overlayView : display) {
overlayView.setSelected(false);
for (final Object overlayInfoObj : selectionValues) {
final OverlayInfo overlayInfo = (OverlayInfo) overlayInfoObj;
if (overlayInfo.getOverlay() == overlayView.getData()) {
overlayInfo.setSelected(true);
overlayView.setSelected(true);
break;
}
}
}
selecting = false;
}
};
jlist.addListSelectionListener(listSelectionListener);
}
// -- private helpers for constructing popup menu --
private JPopupMenu getPopupMenu() {
if (popupMenu == null)
popupMenu = createPopupMenu();
return popupMenu;
}
private JPopupMenu createPopupMenu() {
final JPopupMenu menu = new JPopupMenu();
menu.add(getOpenMenuItem());
menu.add(getSaveMenuItem());
menu.add(getAndMenuItem());
menu.add(getOrMenuItem());
menu.add(getXorMenuItem());
menu.add(getSplitMenuItem());
menu.add(getAddParticlesMenuItem());
menu.add(getMultiMeasureMenuItem());
menu.add(getMultiPlotMenuItem());
menu.add(getSortMenuItem());
menu.add(getSpecifyMenuItem());
menu.add(getRemoveSliceInfoMenuItem());
menu.add(getHelpMenuItem());
menu.add(getOptionsMenuItem());
return menu;
}
private JMenuItem getAddParticlesMenuItem() {
final JMenuItem item;
item = new JMenuItem("Add Particles");
item.setActionCommand(ACTION_ADD_PARTICLES);
item.addActionListener(this);
return item;
}
private JMenuItem getAndMenuItem() {
final JMenuItem item;
item = new JMenuItem("AND");
item.setActionCommand(ACTION_AND);
item.addActionListener(this);
return item;
}
private JMenuItem getHelpMenuItem() {
final JMenuItem item;
item = new JMenuItem("Help");
item.setActionCommand(ACTION_HELP);
item.addActionListener(this);
return item;
}
private JMenuItem getMultiMeasureMenuItem() {
final JMenuItem item;
item = new JMenuItem("Multi Measure");
item.setActionCommand(ACTION_MULTI_MEASURE);
item.addActionListener(this);
return item;
}
private JMenuItem getMultiPlotMenuItem() {
final JMenuItem item;
item = new JMenuItem("Multi Plot");
item.setActionCommand(ACTION_MULTI_PLOT);
item.addActionListener(this);
return item;
}
private JMenuItem getOpenMenuItem() {
final JMenuItem item;
item = new JMenuItem("Open...");
item.setActionCommand(ACTION_OPEN);
item.addActionListener(this);
return item;
}
private JMenuItem getOptionsMenuItem() {
final JMenuItem item;
item = new JMenuItem("Options...");
item.setActionCommand(ACTION_OPTIONS);
item.addActionListener(this);
return item;
}
private JMenuItem getOrMenuItem() {
final JMenuItem item;
item = new JMenuItem("OR (Combine)");
item.setActionCommand(ACTION_OR);
item.addActionListener(this);
return item;
}
private JMenuItem getRemoveSliceInfoMenuItem() {
final JMenuItem item;
item = new JMenuItem("Remove Slice Info");
item.setActionCommand(ACTION_REMOVE_SLICE_INFO);
item.addActionListener(this);
return item;
}
private JMenuItem getSaveMenuItem() {
final JMenuItem item;
item = new JMenuItem("Save...");
item.setActionCommand(ACTION_SAVE);
item.addActionListener(this);
return item;
}
private JMenuItem getSortMenuItem() {
final JMenuItem item;
item = new JMenuItem("Sort");
item.setActionCommand(ACTION_SORT);
item.addActionListener(this);
return item;
}
private JMenuItem getSpecifyMenuItem() {
final JMenuItem item;
item = new JMenuItem("Specify...");
item.setActionCommand(ACTION_SPECIFY);
item.addActionListener(this);
return item;
}
private JMenuItem getSplitMenuItem() {
final JMenuItem item;
item = new JMenuItem("Split");
item.setActionCommand(ACTION_SPLIT);
item.addActionListener(this);
return item;
}
private JMenuItem getXorMenuItem() {
final JMenuItem item;
item = new JMenuItem("XOR");
item.setActionCommand(ACTION_XOR);
item.addActionListener(this);
return item;
}
// -- private helpers to implement main pane button controls --
/* no longer supported
private JButton getAddButton() {
final JButton button = new JButton("Add [t]");
button.setActionCommand(ACTION_ADD);
button.addActionListener(this);
return button;
}
*/
private JButton getDeleteButton() {
final JButton button = new JButton("Delete");
button.setActionCommand(ACTION_DELETE);
button.addActionListener(this);
return button;
}
private JButton getDeselectButton() {
final JButton button = new JButton("Deselect");
button.setActionCommand(ACTION_DESELECT);
button.addActionListener(this);
return button;
}
private JButton getDrawButton() {
final JButton button = new JButton("Draw");
button.setActionCommand(ACTION_DRAW);
button.addActionListener(this);
return button;
}
private JButton getFillButton() {
final JButton button = new JButton("Fill");
button.setActionCommand(ACTION_FILL);
button.addActionListener(this);
return button;
}
private JButton getFlattenButton() {
final JButton button = new JButton("Flatten [f]");
button.setActionCommand(ACTION_FLATTEN);
button.addActionListener(this);
return button;
}
private JButton getMeasureButton() {
final JButton button = new JButton("Measure");
button.setActionCommand(ACTION_MEASURE);
button.addActionListener(this);
return button;
}
private JButton getMoreButton() {
final JButton button = new JButton("More "+'\u00bb');
button.addMouseListener(new MouseListener() {
@Override
@SuppressWarnings("synthetic-access")
public void mouseClicked(MouseEvent e) {
getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
}
@Override
public void mouseEntered(MouseEvent evt) { /* do nothing */ }
@Override
public void mouseExited(MouseEvent evt) { /* do nothing */ }
@Override
public void mousePressed(MouseEvent evt) { /* do nothing */ }
@Override
public void mouseReleased(MouseEvent evt) { /* do nothing */ }
});
return button;
}
private JButton getPropertiesButton() {
final JButton button = new JButton("Properties...");
button.setActionCommand(ACTION_PROPERTIES);
button.addActionListener(this);
return button;
}
private JButton getRenameButton() {
final JButton button = new JButton("Rename...");
button.setActionCommand(ACTION_RENAME);
button.addActionListener(this);
return button;
}
/* no longer supported
private JButton getUpdateButton() {
final JButton button = new JButton("Update");
button.setActionCommand(ACTION_UPDATE);
button.addActionListener(this);
return button;
}
*/
// -- private helpers to change state when checkboxes change --
// TODO
@Override
public void itemStateChanged(ItemEvent evt) {
final boolean selected = (evt.getStateChange() == ItemEvent.SELECTED);
if (evt.getSource() == showAllCheckBox) {
//System.out.println("show all is now "+selected);
}
if (evt.getSource() == editModeCheckBox) {
//System.out.println("edit mode is now "+selected);
// link both checkboxes in selected case
if (selected)
showAllCheckBox.setSelected(true);
}
}
// -- private helpers for TODO XXXX --
// TODO - assumes first selected overlay view is the only one. bad?
@SuppressWarnings("unused")
private Overlay getActiveOverlay() {
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay activeDisplay = ids.getActiveImageDisplay();
if (activeDisplay == null) return null;
final List<DataView> views = activeDisplay;
for (DataView view : views) {
if (view.isSelected() && (view instanceof OverlayView))
return ((OverlayView) view).getData();
}
return null;
}
private void runPropertiesPlugin() {
final Map<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put("overlays", ovrSrv.getOverlayInfo().selectedOverlays());
PluginService pluginService = context.getService(PluginService.class);
pluginService.run(SelectedManagerOverlayProperties.class, inputMap);
}
private ChannelCollection getChannels() {
final OptionsService oSrv = context.getService(OptionsService.class);
OptionsChannels opts = oSrv.getOptions(OptionsChannels.class);
if (altDown) return opts.getBgValues();
return opts.getFgValues();
}
}
| ui/swing/ui-base/src/main/java/imagej/ui/swing/SwingOverlayManager.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing;
import imagej.ImageJ;
import imagej.core.plugins.overlay.SelectedManagerOverlayProperties;
import imagej.data.ChannelCollection;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.data.ImageGrabber;
import imagej.data.display.DataView;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.display.OverlayInfo;
import imagej.data.display.OverlayInfoList;
import imagej.data.display.OverlayService;
import imagej.data.display.OverlayView;
import imagej.data.display.event.DataViewSelectionEvent;
import imagej.data.event.OverlayCreatedEvent;
import imagej.data.event.OverlayDeletedEvent;
import imagej.data.event.OverlayRestructuredEvent;
import imagej.data.event.OverlayUpdatedEvent;
import imagej.data.overlay.Overlay;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.DisplayService;
import imagej.ext.plugin.PluginService;
import imagej.log.LogService;
import imagej.options.OptionsService;
import imagej.options.plugins.OptionsChannels;
import imagej.platform.PlatformService;
import imagej.util.Prefs;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.imglib2.RandomAccess;
import net.imglib2.display.ARGBScreenImage;
import net.imglib2.img.ImgPlus;
import net.imglib2.meta.Axes;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
// TODO
//
// - implement methods that actually do stuff
// - since it knows its a Swing UI it uses Swing UI features. Ideally we should
// make OverlayManager a Display<Overlay> and work as much as possible in
// an agnostic fashion. Thus no swing style listeners but instead IJ2
// listeners. And rather than swing input dialogs we should make IJ2 input
// dialogs.
/**
* Overlay Manager Swing UI
*
* @author Barry DeZonia
* @author Adam Fraser
*/
public class SwingOverlayManager
extends JFrame
implements ActionListener, ItemListener
{
// -- constants --
//private static final long serialVersionUID = -6498169032123522303L;
// no longer supported
//private static final String ACTION_ADD = "add";
private static final String ACTION_ADD_PARTICLES = "add particles";
private static final String ACTION_AND = "and";
private static final String ACTION_DELETE = "delete";
private static final String ACTION_DESELECT = "deselect";
private static final String ACTION_DRAW = "draw";
private static final String ACTION_FILL = "fill";
private static final String ACTION_FLATTEN = "flatten";
private static final String ACTION_HELP = "help";
private static final String ACTION_MEASURE = "measure";
private static final String ACTION_MULTI_MEASURE = "multi measure";
private static final String ACTION_MULTI_PLOT = "multi plot";
private static final String ACTION_OPEN = "open";
private static final String ACTION_OPTIONS = "options";
private static final String ACTION_OR = "or";
private static final String ACTION_PROPERTIES = "properties";
private static final String ACTION_REMOVE_SLICE_INFO = "remove slice info";
private static final String ACTION_RENAME = "rename";
private static final String ACTION_SAVE = "save";
private static final String ACTION_SORT = "sort";
private static final String ACTION_SPECIFY = "specify";
private static final String ACTION_SPLIT = "split";
// no longer supported
//private static final String ACTION_UPDATE = "update";
private static final String ACTION_XOR = "xor";
private static final String LAST_X = "lastXLocation";
private static final String LAST_Y = "lastYLocation";
// -- instance variables --
/** Maintains the list of event subscribers, to avoid garbage collection. */
@SuppressWarnings("unused")
private final List<EventSubscriber<?>> subscribers;
private final ImageJ context;
private final JList jlist;
private boolean selecting = false; // flag to prevent event feedback loops
private JPopupMenu popupMenu = null;
private final JCheckBox showAllCheckBox;
private final JCheckBox editModeCheckBox;
private boolean shiftDown = false;
private boolean altDown = false;
private final OverlayService ovrSrv;
// -- constructor --
/**
* Creates a JList to list the overlays.
*/
public SwingOverlayManager(final ImageJ context) {
this.context = context;
this.ovrSrv = context.getService(OverlayService.class);
jlist = new JList(new OverlayListModel(ovrSrv.getOverlayInfo()));
//jlist.setCellRenderer(new OverlayRenderer());
final JScrollPane listScroller = new JScrollPane(jlist);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
final JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
listPanel.add(listScroller);
listPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
final JPanel buttonPane = new JPanel();
buttonPane.setLayout(new GridLayout(9,1,5,0));
// NO LONGER SUPPORTING
//buttonPane.add(getAddButton());
//buttonPane.add(getUpdateButton());
buttonPane.add(getDeleteButton());
buttonPane.add(getRenameButton());
buttonPane.add(getMeasureButton());
buttonPane.add(getDeselectButton());
buttonPane.add(getPropertiesButton());
buttonPane.add(getFlattenButton());
buttonPane.add(getFillButton());
buttonPane.add(getDrawButton());
buttonPane.add(getMoreButton());
final JPanel boolPane = new JPanel();
boolPane.setLayout(new BoxLayout(boolPane, BoxLayout.Y_AXIS));
showAllCheckBox = new JCheckBox("Show All",false);
editModeCheckBox = new JCheckBox("Edit Mode",false);
boolPane.add(showAllCheckBox);
boolPane.add(editModeCheckBox);
showAllCheckBox.addItemListener(this);
editModeCheckBox.addItemListener(this);
final JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BorderLayout());
controlPanel.add(buttonPane,BorderLayout.CENTER);
controlPanel.add(boolPane,BorderLayout.SOUTH);
final Container cp = this.getContentPane();
cp.add(listPanel, BorderLayout.CENTER);
cp.add(controlPanel, BorderLayout.EAST);
setTitle("Overlay Manager");
setupListSelectionListener();
setupCloseListener();
setupKeyListener();
restoreLocation();
pack();
final EventService eventService = context.getService(EventService.class);
subscribers = eventService.subscribe(this);
/* NOTE BDZ removed 6-11-12. There should be a default menu bar attached
* to this frame now.
*
// FIXME - temp hack - made this class (which is not a display) make sure
// menu bar available when it is running. Ugly cast in place to create the
// menu bar. A better approach would be to make a new event tied to a menu
// bar listener of some sort. This code could emit that "need a menu bar"
// event here. Filing as ticket.
final UIService uiService = context.getService(UIService.class);
((AbstractSwingUI)uiService.getUI()).createMenuBar(this, false);
*/
populateOverlayList();
}
// -- public interface --
@Override
public void actionPerformed(final ActionEvent e) {
final String command = e.getActionCommand();
if (command == null) return;
/* no longer supported
if (command.equals(ACTION_ADD))
add();
*/
if (command.equals(ACTION_ADD_PARTICLES))
addParticles();
else if (command.equals(ACTION_AND))
and();
else if (command.equals(ACTION_DELETE))
delete();
else if (command.equals(ACTION_DESELECT))
deselect();
else if (command.equals(ACTION_DRAW))
draw();
else if (command.equals(ACTION_FILL))
fill();
else if (command.equals(ACTION_FLATTEN))
flatten();
else if (command.equals(ACTION_HELP))
help();
else if (command.equals(ACTION_MEASURE))
measure();
else if (command.equals(ACTION_MULTI_MEASURE))
multiMeasure();
else if (command.equals(ACTION_MULTI_PLOT))
multiPlot();
else if (command.equals(ACTION_OPEN))
open();
else if (command.equals(ACTION_OPTIONS))
options();
else if (command.equals(ACTION_OR))
or();
else if (command.equals(ACTION_PROPERTIES))
properties();
else if (command.equals(ACTION_REMOVE_SLICE_INFO))
removeSliceInfo();
else if (command.equals(ACTION_RENAME))
rename();
else if (command.equals(ACTION_SAVE))
save();
else if (command.equals(ACTION_SORT))
sort();
else if (command.equals(ACTION_SPECIFY))
specify();
else if (command.equals(ACTION_SPLIT))
split();
/*
else if (command.equals(ACTION_UPDATE))
update();
*/
else if (command.equals(ACTION_XOR))
xor();
}
// -- private helpers for overlay list maintenance --
private class OverlayListModel extends AbstractListModel {
//private static final long serialVersionUID = 7941252533859436640L;
private OverlayInfoList overlayInfoList;
public OverlayListModel(OverlayInfoList list) {
overlayInfoList = list;
}
@Override
public Object getElementAt(final int index) {
return overlayInfoList.getOverlayInfo(index);
}
@Override
public int getSize() {
return overlayInfoList.getOverlayInfoCount();
}
}
/*
*/
private void populateOverlayList() {
// Populate the list with all overlays
for (final Overlay overlay : ovrSrv.getOverlays()) {
boolean found = false;
int totOverlays = ovrSrv.getOverlayInfo().getOverlayInfoCount();
for (int i = 0; i < totOverlays; i++) {
OverlayInfo info = ovrSrv.getOverlayInfo().getOverlayInfo(i);
if (overlay == info.getOverlay()) {
found = true;
break;
}
}
if (!found) {
OverlayInfo info = new OverlayInfo(overlay);
ovrSrv.getOverlayInfo().addOverlayInfo(info);
}
}
jlist.updateUI();
}
/*
private class OverlayRenderer extends DefaultListCellRenderer {
//private static final long serialVersionUID = 2468086636364454253L;
private final Hashtable<Overlay, ImageIcon> iconTable =
new Hashtable<Overlay, ImageIcon>();
@Override
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean hasFocus)
{
final JLabel label =
(JLabel) super.getListCellRendererComponent(list, value, index,
isSelected, hasFocus);
if (value instanceof Overlay) {
final Overlay overlay = (Overlay) value;
// TODO: create overlay thumbnail from overlay
final ImageIcon icon = iconTable.get(overlay);
// if (icon == null) {
// icon = new ImageIcon(...);
// iconTable.put(overlay, ImageIcon);
// }
label.setIcon(icon);
}
else {
// Clear old icon; needed in 1st release of JDK 1.2
label.setIcon(null);
}
return label;
}
}
*/
// -- event handlers --
@EventHandler
protected void onEvent(final OverlayCreatedEvent event) {
//System.out.println("\tCREATED: " + event.toString());
ovrSrv.getOverlayInfo().addOverlay(event.getObject());
jlist.updateUI();
}
@EventHandler
protected void onEvent(final OverlayDeletedEvent event) {
//System.out.println("\tDELETED: " + event.toString());
Overlay overlay = event.getObject();
ovrSrv.getOverlayInfo().deleteOverlay(overlay);
int[] newSelectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(newSelectedIndices);
jlist.updateUI();
}
/*
// Update when a display is activated.
@EventHandler
protected void onEvent(
@SuppressWarnings("unused") final DisplayActivatedEvent event)
{
jlist.updateUI();
}
*/
@EventHandler
protected void onEvent(final DataViewSelectionEvent event) {
if (selecting) return;
selecting = true;
// Select or deselect the corresponding overlay in the list
final Overlay overlay = (Overlay) event.getView().getData();
final int overlayIndex = ovrSrv.getOverlayInfo().findIndex(overlay);
final OverlayInfo overlayInfo = ovrSrv.getOverlayInfo().getOverlayInfo(overlayIndex);
overlayInfo.setSelected(event.isSelected());
/* old way
if (event.isSelected()) {
final int[] current_sel = jlist.getSelectedIndices();
jlist.setSelectedValue(overlayInfo, true);
final int[] new_sel = jlist.getSelectedIndices();
final int[] sel =
Arrays.copyOf(current_sel, current_sel.length + new_sel.length);
System.arraycopy(new_sel, 0, sel, current_sel.length, new_sel.length);
jlist.setSelectedIndices(sel);
}
else {
for (final int i : jlist.getSelectedIndices()) {
if (jlist.getModel().getElementAt(i) == overlayInfo) {
jlist.removeSelectionInterval(i, i);
}
}
}
*/
int[] selections = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(selections);
selecting = false;
}
/*
// TODO - this may not be best way to do this
// Its here to allow acceleration without ALT/OPTION key
// Maybe make buttons listen for actions
@EventHandler
protected void onKeyPressedEvent(KyPressedEvent ev) {
System.out.println("key press registered to display "+ev.getDisplay());
altDown = ev.getModifiers().isAltDown() || ev.getModifiers().isAltGrDown();
shiftDown = ev.getModifiers().isShiftDown();
KeyCode key = ev.getCode();
if (key == KeyCode.T) add();
if (key == KeyCode.F) flatten();
if (key == KeyCode.DELETE) delete();
}
*/
@SuppressWarnings("unused")
@EventHandler
protected void onEvent(OverlayRestructuredEvent event) {
//System.out.println("restructured");
jlist.updateUI();
}
@SuppressWarnings("unused")
@EventHandler
protected void onEvent(OverlayUpdatedEvent event) {
//System.out.println("updated");
jlist.updateUI();
}
// -- private helpers that implement overlay interaction commands --
/* no longer supported
private void add() {
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay activeDisplay = ids.getActiveImageDisplay();
if (activeDisplay == null) return;
final List<DataView> views = activeDisplay;
boolean additions = false;
for (DataView view : views) {
if (view.isSelected() && (view instanceof OverlayView))
additions |= infoList.addOverlay((Overlay)view.getData());
}
if (additions)
jlist.updateUI();
}
*/
private void addParticles() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void and() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void delete() {
if (ovrSrv.getOverlayInfo().getOverlayInfoCount() == 0) return;
List<Overlay> overlaysToDelete = new LinkedList<Overlay>();
final int[] selectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
if (selectedIndices.length == 0) {
final int result =
JOptionPane.showConfirmDialog(
this, "Delete all overlays?", "Delete All", JOptionPane.YES_NO_OPTION);
if (result != JOptionPane.YES_OPTION) return;
for (int i = 0; i < ovrSrv.getOverlayInfo().getOverlayInfoCount(); i++) {
overlaysToDelete.add(ovrSrv.getOverlayInfo().getOverlayInfo(i).getOverlay());
}
}
else {
for (int i = 0; i < selectedIndices.length; i++) {
int index = selectedIndices[i];
overlaysToDelete.add(ovrSrv.getOverlayInfo().getOverlayInfo(index).getOverlay());
}
}
for (Overlay overlay : overlaysToDelete) {
// NB - removeOverlay() can indirectly change our infoList contents.
// Thus we first collect overlays from the infoList and then delete
// them all afterwards to avoid interactions.
ovrSrv.removeOverlay(overlay);
}
}
private void deselect() {
ovrSrv.getOverlayInfo().deselectAll();
jlist.clearSelection();
}
private void draw() {
OverlayService os = context.getService(OverlayService.class);
ChannelCollection channels = getChannels();
List<Overlay> selected = ovrSrv.getOverlayInfo().selectedOverlays();
for (Overlay o : selected) {
ImageDisplay disp = os.getFirstDisplay(o);
os.drawOverlay(o, disp, channels);
}
}
private void fill() {
OverlayService os = context.getService(OverlayService.class);
ChannelCollection channels = getChannels();
List<Overlay> selected = ovrSrv.getOverlayInfo().selectedOverlays();
for (Overlay o : selected) {
ImageDisplay disp = os.getFirstDisplay(o);
os.fillOverlay(o, disp, channels);
}
}
/* FIXME TODO notes
* I'm pretty sure this just snapshots the current view and returns a new
* Dataset/Img that is one dimensional, usually rgb, and shows drawn rois.
* If show all is true it draws all rois, else it draws curr roi. Note that
* we can get rid of show all I think because we always show all. Is that a
* problem? Edit mode renders differently. This might affect OverlayService
* for drawOverlay() and fillOverlay(). Do we need a way to show single
* overlays now? Probably. More hints for OverlayService I suppose. Anyhow
* we should be able to grab the current view's (or the active overlay's
* view's) ARGBScreenImage and create a new Dataset from it. We could make a
* capture() method to ImageDisplay. Right now this implementation does not
* show the ROI outline. Thats all the special case code the ROI Mgr flatten
* does compared to the menu command flatten. We need a way to tell the
* OverlayService to draw an Overlay in a given Dataset. But we want to draw
* using fg/bg sometimes and using default drawing capabilities sometimes
* (like JHotDraw's rendering). Ideally capture window exactly as is but
* without mouse cursor. Right?
*/
private void flatten() {
/*
List<Overlay> selOverlays = infoList.selectedOverlays();
if (selOverlays.size() == 0) {
JOptionPane.showMessageDialog(this, "At least one overlay must be selected");
return;
}
*/
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay imageDisplay = ids.getActiveImageDisplay();
if (imageDisplay == null) return;
final DatasetView view = ids.getActiveDatasetView(imageDisplay);
if (view == null) return;
DatasetService dss = context.getService(DatasetService.class);
String datasetName = imageDisplay.getName() + " - flattened";
Dataset dataset = new ImageGrabber(dss).grab(view, datasetName);
DisplayService ds = context.getService(DisplayService.class);
ds.createDisplay(dataset.getName(), dataset);
// TODO - This currently does not show the ROI outline
}
private void help() {
LogService log = context.getService(LogService.class);
log.warn("TODO in SwingOverlayManager::help() - using old IJ1 URL for this command");
final PlatformService ps = context.getService(PlatformService.class);
try {
final URL url =
new URL("http://imagej.nih.gov/ij/docs/menus/analyze.html#manager");
ps.open(url);
} catch (IOException e) {
// do nothing
}
}
private void measure() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void multiMeasure() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void multiPlot() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void open() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void options() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void or() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void properties() {
int[] selected = ovrSrv.getOverlayInfo().selectedIndices();
if (selected.length == 0) {
JOptionPane.showMessageDialog(this, "This command requires one or more selections");
return;
}
// else one or more selections exist
runPropertiesPlugin();
}
private void removeSliceInfo() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void rename() {
final int[] selectedIndices = ovrSrv.getOverlayInfo().selectedIndices();
if (selectedIndices.length < 1) {
JOptionPane.showMessageDialog(this, "Must select an overlay to rename");
return;
}
if (selectedIndices.length > 1) {
JOptionPane.showMessageDialog(this, "Cannot rename multiple overlays simultaneously");
return;
}
final OverlayInfo info = ovrSrv.getOverlayInfo().getOverlayInfo(selectedIndices[0]);
if (info == null) return;
// TODO - UI agnostic way here
final String name = JOptionPane.showInputDialog(this, "Enter new name for overlay");
if ((name == null) || (name.length() == 0))
info.getOverlay().setName(null);
else
info.getOverlay().setName(name);
jlist.updateUI();
}
private void save() {
JOptionPane.showMessageDialog(this, "unimplemented");
/*
final int[] selectedIndices = jlist.getSelectedIndices();
// nothing selected
if (selectedIndices.length == 0) {
JOptionPane.showMessageDialog(this, "Cannot save - one or more overlays must be selected first");
return;
}
final JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save Overlay to file ...");
chooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter1, filter2;
filter1 = new FileNameExtensionFilter("ImageJ overlay containers (*.zip)", "zip");
chooser.addChoosableFileFilter(filter1);
filter2 = new FileNameExtensionFilter("ImageJ overlay files (*.ovl)", "ovl");
chooser.addChoosableFileFilter(filter2);
chooser.setFileFilter(filter2);
int result = chooser.showSaveDialog(this);
if (result != JFileChooser.APPROVE_OPTION) return;
String basename = chooser.getSelectedFile().getAbsolutePath();
if (basename.toLowerCase().endsWith(".ovl") ||
basename.toLowerCase().endsWith(".zip")) {
basename = basename.substring(0,basename.length()-4);
}
// one roi selected
if (selectedIndices.length == 1) {
// save overlay in its own user named .ovl file
String filename = basename + ".ovl";
final OverlayInfo info = (OverlayInfo) jlist.getSelectedValue();
//info.overlay.save(filename);
}
else { // more than one roi selected
// save each overlay in its own .ovl file in a user named .zip container
String filename = basename + ".zip";
JOptionPane.showMessageDialog(this, "save multiple overlays to zip is unimplemented");
}
*/
}
private void sort() {
ovrSrv.getOverlayInfo().sort();
int[] newSelections = ovrSrv.getOverlayInfo().selectedIndices();
jlist.setSelectedIndices(newSelections);
jlist.updateUI();
}
private void specify() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
private void split() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
/*
* old functionality : now that all overlays always tracked this no longer
* makes sense
*
// replace OverlayInfoList's currently selected info with the currently
// selected roi
private void update() {
final int[] selectedIndices = infoList.selectedIndices();
if (selectedIndices.length != 1) {
JOptionPane.showMessageDialog(this,
"Exactly one item must be selected");
return;
}
final Overlay overlay = getActiveOverlay();
if (overlay == null) {
JOptionPane.showMessageDialog(this,
"An overlay must be selected in the current view");
return;
}
final int index = infoList.findIndex(overlay);
if (index != -1) {
// already in list
if (index != selectedIndices[0])
JOptionPane.showMessageDialog(this,
"Selected overlay is already tracked by the overlay manager");
return;
}
infoList.replaceOverlay(selectedIndices[0], overlay);
jlist.updateUI();
}
*/
private void xor() {
JOptionPane.showMessageDialog(this, "unimplemented");
}
// -- private helpers for hotkey handling --
private void setupKeyListener() {
//KeyListener listener = new AWTKeyEventDispatcher(fakeDisplay, eventService);
final KeyListener listener = new KeyListener() {
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
altDown = e.isAltDown() || e.isAltGraphDown();
shiftDown = e.isShiftDown();
/* no longer supported
if (e.getKeyCode() == KeyEvent.VK_T) add();
*/
if (e.getKeyCode() == KeyEvent.VK_F) flatten();
if (e.getKeyCode() == KeyEvent.VK_DELETE) delete();
}
@Override
@SuppressWarnings("synthetic-access")
public void keyReleased(KeyEvent e) {
altDown = e.isAltDown() || e.isAltGraphDown();
shiftDown = e.isShiftDown();
}
@Override
public void keyTyped(KeyEvent e) { /* do nothing */ }
};
final Stack<Component> stack = new Stack<Component>();
stack.push(this);
while (!stack.empty()) {
final Component component = stack.pop();
component.addKeyListener(listener);
if (component instanceof Container) {
final Container container = (Container) component;
for (Component c : container.getComponents())
stack.push(c);
}
}
}
// -- private helpers for frame location --
/** Persists the application frame's current location. */
private void saveLocation() {
Prefs.put(getClass(), LAST_X, getLocation().x);
Prefs.put(getClass(), LAST_Y, getLocation().y);
}
/** Restores the application frame's current location. */
private void restoreLocation() {
final int lastX = Prefs.getInt(getClass(), LAST_X, 0);
final int lastY = Prefs.getInt(getClass(), LAST_Y, 0);
setLocation(lastX, lastY);
}
private void setupCloseListener() {
addWindowListener(new WindowAdapter() {
@Override
@SuppressWarnings("synthetic-access")
public void windowClosing(WindowEvent e) {
// Remember screen location of window for next time
saveLocation();
}
});
}
// -- private helpers for list selection event listening --
private void setupListSelectionListener() {
final ListSelectionListener
listSelectionListener = new ListSelectionListener() {
@Override
@SuppressWarnings("synthetic-access")
public void valueChanged(final ListSelectionEvent listSelectionEvent) {
if (selecting) return;
selecting = true;
final ImageDisplayService imageDisplayService =
context.getService(ImageDisplayService.class);
final ImageDisplay display =
imageDisplayService.getActiveImageDisplay();
if (display == null) return;
final JList list = (JList) listSelectionEvent.getSource();
final Object[] selectionValues = list.getSelectedValues();
ovrSrv.getOverlayInfo().deselectAll();
for (final Object overlayInfoObj : selectionValues) {
final OverlayInfo overlayInfo = (OverlayInfo) overlayInfoObj;
overlayInfo.setSelected(true);
}
for (final DataView overlayView : display) {
overlayView.setSelected(false);
for (final Object overlayInfoObj : selectionValues) {
final OverlayInfo overlayInfo = (OverlayInfo) overlayInfoObj;
if (overlayInfo.getOverlay() == overlayView.getData()) {
overlayInfo.setSelected(true);
overlayView.setSelected(true);
break;
}
}
}
selecting = false;
}
};
jlist.addListSelectionListener(listSelectionListener);
}
// -- private helpers for constructing popup menu --
private JPopupMenu getPopupMenu() {
if (popupMenu == null)
popupMenu = createPopupMenu();
return popupMenu;
}
private JPopupMenu createPopupMenu() {
final JPopupMenu menu = new JPopupMenu();
menu.add(getOpenMenuItem());
menu.add(getSaveMenuItem());
menu.add(getAndMenuItem());
menu.add(getOrMenuItem());
menu.add(getXorMenuItem());
menu.add(getSplitMenuItem());
menu.add(getAddParticlesMenuItem());
menu.add(getMultiMeasureMenuItem());
menu.add(getMultiPlotMenuItem());
menu.add(getSortMenuItem());
menu.add(getSpecifyMenuItem());
menu.add(getRemoveSliceInfoMenuItem());
menu.add(getHelpMenuItem());
menu.add(getOptionsMenuItem());
return menu;
}
private JMenuItem getAddParticlesMenuItem() {
final JMenuItem item;
item = new JMenuItem("Add Particles");
item.setActionCommand(ACTION_ADD_PARTICLES);
item.addActionListener(this);
return item;
}
private JMenuItem getAndMenuItem() {
final JMenuItem item;
item = new JMenuItem("AND");
item.setActionCommand(ACTION_AND);
item.addActionListener(this);
return item;
}
private JMenuItem getHelpMenuItem() {
final JMenuItem item;
item = new JMenuItem("Help");
item.setActionCommand(ACTION_HELP);
item.addActionListener(this);
return item;
}
private JMenuItem getMultiMeasureMenuItem() {
final JMenuItem item;
item = new JMenuItem("Multi Measure");
item.setActionCommand(ACTION_MULTI_MEASURE);
item.addActionListener(this);
return item;
}
private JMenuItem getMultiPlotMenuItem() {
final JMenuItem item;
item = new JMenuItem("Multi Plot");
item.setActionCommand(ACTION_MULTI_PLOT);
item.addActionListener(this);
return item;
}
private JMenuItem getOpenMenuItem() {
final JMenuItem item;
item = new JMenuItem("Open...");
item.setActionCommand(ACTION_OPEN);
item.addActionListener(this);
return item;
}
private JMenuItem getOptionsMenuItem() {
final JMenuItem item;
item = new JMenuItem("Options...");
item.setActionCommand(ACTION_OPTIONS);
item.addActionListener(this);
return item;
}
private JMenuItem getOrMenuItem() {
final JMenuItem item;
item = new JMenuItem("OR (Combine)");
item.setActionCommand(ACTION_OR);
item.addActionListener(this);
return item;
}
private JMenuItem getRemoveSliceInfoMenuItem() {
final JMenuItem item;
item = new JMenuItem("Remove Slice Info");
item.setActionCommand(ACTION_REMOVE_SLICE_INFO);
item.addActionListener(this);
return item;
}
private JMenuItem getSaveMenuItem() {
final JMenuItem item;
item = new JMenuItem("Save...");
item.setActionCommand(ACTION_SAVE);
item.addActionListener(this);
return item;
}
private JMenuItem getSortMenuItem() {
final JMenuItem item;
item = new JMenuItem("Sort");
item.setActionCommand(ACTION_SORT);
item.addActionListener(this);
return item;
}
private JMenuItem getSpecifyMenuItem() {
final JMenuItem item;
item = new JMenuItem("Specify...");
item.setActionCommand(ACTION_SPECIFY);
item.addActionListener(this);
return item;
}
private JMenuItem getSplitMenuItem() {
final JMenuItem item;
item = new JMenuItem("Split");
item.setActionCommand(ACTION_SPLIT);
item.addActionListener(this);
return item;
}
private JMenuItem getXorMenuItem() {
final JMenuItem item;
item = new JMenuItem("XOR");
item.setActionCommand(ACTION_XOR);
item.addActionListener(this);
return item;
}
// -- private helpers to implement main pane button controls --
/* no longer supported
private JButton getAddButton() {
final JButton button = new JButton("Add [t]");
button.setActionCommand(ACTION_ADD);
button.addActionListener(this);
return button;
}
*/
private JButton getDeleteButton() {
final JButton button = new JButton("Delete");
button.setActionCommand(ACTION_DELETE);
button.addActionListener(this);
return button;
}
private JButton getDeselectButton() {
final JButton button = new JButton("Deselect");
button.setActionCommand(ACTION_DESELECT);
button.addActionListener(this);
return button;
}
private JButton getDrawButton() {
final JButton button = new JButton("Draw");
button.setActionCommand(ACTION_DRAW);
button.addActionListener(this);
return button;
}
private JButton getFillButton() {
final JButton button = new JButton("Fill");
button.setActionCommand(ACTION_FILL);
button.addActionListener(this);
return button;
}
private JButton getFlattenButton() {
final JButton button = new JButton("Flatten [f]");
button.setActionCommand(ACTION_FLATTEN);
button.addActionListener(this);
return button;
}
private JButton getMeasureButton() {
final JButton button = new JButton("Measure");
button.setActionCommand(ACTION_MEASURE);
button.addActionListener(this);
return button;
}
private JButton getMoreButton() {
final JButton button = new JButton("More "+'\u00bb');
button.addMouseListener(new MouseListener() {
@Override
@SuppressWarnings("synthetic-access")
public void mouseClicked(MouseEvent e) {
getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
}
@Override
public void mouseEntered(MouseEvent evt) { /* do nothing */ }
@Override
public void mouseExited(MouseEvent evt) { /* do nothing */ }
@Override
public void mousePressed(MouseEvent evt) { /* do nothing */ }
@Override
public void mouseReleased(MouseEvent evt) { /* do nothing */ }
});
return button;
}
private JButton getPropertiesButton() {
final JButton button = new JButton("Properties...");
button.setActionCommand(ACTION_PROPERTIES);
button.addActionListener(this);
return button;
}
private JButton getRenameButton() {
final JButton button = new JButton("Rename...");
button.setActionCommand(ACTION_RENAME);
button.addActionListener(this);
return button;
}
/* no longer supported
private JButton getUpdateButton() {
final JButton button = new JButton("Update");
button.setActionCommand(ACTION_UPDATE);
button.addActionListener(this);
return button;
}
*/
// -- private helpers to change state when checkboxes change --
// TODO
@Override
public void itemStateChanged(ItemEvent evt) {
final boolean selected = (evt.getStateChange() == ItemEvent.SELECTED);
if (evt.getSource() == showAllCheckBox) {
//System.out.println("show all is now "+selected);
}
if (evt.getSource() == editModeCheckBox) {
//System.out.println("edit mode is now "+selected);
// link both checkboxes in selected case
if (selected)
showAllCheckBox.setSelected(true);
}
}
// -- private helpers for TODO XXXX --
// TODO - assumes first selected overlay view is the only one. bad?
@SuppressWarnings("unused")
private Overlay getActiveOverlay() {
final ImageDisplayService ids = context.getService(ImageDisplayService.class);
final ImageDisplay activeDisplay = ids.getActiveImageDisplay();
if (activeDisplay == null) return null;
final List<DataView> views = activeDisplay;
for (DataView view : views) {
if (view.isSelected() && (view instanceof OverlayView))
return ((OverlayView) view).getData();
}
return null;
}
private void runPropertiesPlugin() {
final Map<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put("overlays", ovrSrv.getOverlayInfo().selectedOverlays());
PluginService pluginService = context.getService(PluginService.class);
pluginService.run(SelectedManagerOverlayProperties.class, inputMap);
/*
String name = info.toString();
ColorRGB lineColor = info.overlay.getLineColor();
ColorRGB fillColor = info.overlay.getFillColor();
double width = info.overlay.getLineWidth();
JOptionPane.showMessageDialog(this,
"(" + name +
") (" + lineColor +
") (" + fillColor +
") (" + width + ")");
*/
}
private ChannelCollection getChannels() {
final OptionsService oSrv = context.getService(OptionsService.class);
OptionsChannels opts = oSrv.getOptions(OptionsChannels.class);
if (altDown) return opts.getBgValues();
return opts.getFgValues();
}
}
| clean up imports and improve documentation
| ui/swing/ui-base/src/main/java/imagej/ui/swing/SwingOverlayManager.java | clean up imports and improve documentation | <ide><path>i/swing/ui-base/src/main/java/imagej/ui/swing/SwingOverlayManager.java
<ide> import javax.swing.JScrollPane;
<ide> import javax.swing.event.ListSelectionEvent;
<ide> import javax.swing.event.ListSelectionListener;
<del>
<del>import net.imglib2.RandomAccess;
<del>import net.imglib2.display.ARGBScreenImage;
<del>import net.imglib2.img.ImgPlus;
<del>import net.imglib2.meta.Axes;
<del>import net.imglib2.type.numeric.RealType;
<del>import net.imglib2.type.numeric.integer.UnsignedByteType;
<ide>
<ide> // TODO
<ide> //
<ide> * problem? Edit mode renders differently. This might affect OverlayService
<ide> * for drawOverlay() and fillOverlay(). Do we need a way to show single
<ide> * overlays now? Probably. More hints for OverlayService I suppose. Anyhow
<del> * we should be able to grab the current view's (or the active overlay's
<del> * view's) ARGBScreenImage and create a new Dataset from it. We could make a
<del> * capture() method to ImageDisplay. Right now this implementation does not
<del> * show the ROI outline. Thats all the special case code the ROI Mgr flatten
<del> * does compared to the menu command flatten. We need a way to tell the
<del> * OverlayService to draw an Overlay in a given Dataset. But we want to draw
<del> * using fg/bg sometimes and using default drawing capabilities sometimes
<del> * (like JHotDraw's rendering). Ideally capture window exactly as is but
<del> * without mouse cursor. Right?
<add> * we grab the current view as a merged color dataset using an ImageGrabber.
<add> * Right now this implementation does not show the ROI outline. Thats all the
<add> * special case code the ROI Mgr flatten does compared to the menu command
<add> * flatten. We need a way to tell the OverlayService to draw an Overlay in a
<add> * given Dataset. But we want to draw using fg/bg sometimes and using default
<add> * drawing capabilities sometimes (like JHotDraw's rendering).
<ide> */
<ide> private void flatten() {
<ide> /*
<ide> inputMap.put("overlays", ovrSrv.getOverlayInfo().selectedOverlays());
<ide> PluginService pluginService = context.getService(PluginService.class);
<ide> pluginService.run(SelectedManagerOverlayProperties.class, inputMap);
<del> /*
<del> String name = info.toString();
<del> ColorRGB lineColor = info.overlay.getLineColor();
<del> ColorRGB fillColor = info.overlay.getFillColor();
<del> double width = info.overlay.getLineWidth();
<del> JOptionPane.showMessageDialog(this,
<del> "(" + name +
<del> ") (" + lineColor +
<del> ") (" + fillColor +
<del> ") (" + width + ")");
<del> */
<ide> }
<ide>
<ide> private ChannelCollection getChannels() { |
|
Java | apache-2.0 | 8985436cf406b2af15ebfe03462875cc641573e2 | 0 | mosaic-cloud/mosaic-java-platform,mosaic-cloud/mosaic-java-platform | /*
* #%L
* mosaic-tools-threading
* %%
* Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania)
* %%
* 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%
*/
// $codepro.audit.disable emptyCatchClause
// $codepro.audit.disable logExceptions
package eu.mosaic_cloud.tools.threading.tools;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import eu.mosaic_cloud.tools.exceptions.core.ExceptionTracer;
import eu.mosaic_cloud.tools.exceptions.tools.AbortingExceptionTracer;
import eu.mosaic_cloud.tools.threading.core.ThreadConfiguration;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext.ManagedThread;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext.ManagedThreadGroup;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Atomics;
public final class Threading
extends Object
{
private Threading ()
{
super ();
throw (new UnsupportedOperationException ());
}
public static final boolean acquire (final Semaphore semaphore)
{
return (Threading.acquire (semaphore, 1));
}
public static final boolean acquire (final Semaphore semaphore, final int tokens)
{
return (Threading.acquire (semaphore, tokens, -1));
}
public static final boolean acquire (final Semaphore semaphore, final int tokens, final long timeout)
{
Preconditions.checkNotNull (semaphore);
Preconditions.checkArgument (tokens >= 0);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (semaphore.tryAcquire (tokens, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (semaphore.tryAcquire ());
else if (timeout == -1) {
semaphore.acquire (tokens);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean acquire (final Semaphore semaphore, final long timeout)
{
return (Threading.acquire (semaphore, 1, timeout));
}
public static final boolean await (final Condition condition)
{
return (Threading.await (condition, -1));
}
public static final boolean await (final Condition condition, final long timeout)
{
Preconditions.checkNotNull (condition);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (condition.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1) {
condition.await ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean await (final CountDownLatch latch)
{
return (Threading.await (latch, -1));
}
public static final boolean await (final CountDownLatch latch, final long timeout)
{
Preconditions.checkNotNull (latch);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (latch.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1) {
latch.await ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final int await (final CyclicBarrier barrier)
{
return (Threading.await (barrier, -1));
}
public static final int await (final CyclicBarrier barrier, final long timeout)
{
Preconditions.checkNotNull (barrier);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (barrier.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1)
return (barrier.await ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (-1);
} catch (final TimeoutException exception) {
return (-1);
} catch (final BrokenBarrierException exception) {
return (-1);
}
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future)
throws ExecutionException
{
return (Threading.await (future, null));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final _Object_ timeoutMarker)
throws ExecutionException
{
return (Threading.await (future, -1, timeoutMarker));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final long timeout)
throws ExecutionException
{
return (Threading.await (future, timeout, null));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final long timeout, final _Object_ timeoutMarker)
throws ExecutionException
{
Preconditions.checkNotNull (future);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final _Object_ received;
if (timeout >= 0)
received = future.get (timeout, TimeUnit.MILLISECONDS);
else if (timeout == -1)
received = future.get ();
else
throw (new AssertionError ());
return (received);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (timeoutMarker);
} catch (final TimeoutException exception) {
return (timeoutMarker);
}
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future)
{
return (Threading.awaitOrCatch (future, null, null));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final _Object_ timeoutMarker, final _Object_ exceptionMarker)
{
return (Threading.awaitOrCatch (future, -1, timeoutMarker, exceptionMarker));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final long timeout)
{
return (Threading.awaitOrCatch (future, timeout, null, null));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final long timeout, final _Object_ timeoutMarker, final _Object_ exceptionMarker)
{
try {
return (Threading.await (future, timeout, timeoutMarker));
} catch (final ExecutionException exception) {
return (exceptionMarker);
}
}
public static final Thread createAndStartDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, true), runnable));
}
public static final Thread createAndStartDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, true, exceptions, catcher), runnable));
}
public static final Thread createAndStartNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, false), runnable));
}
public static final Thread createAndStartNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, false, exceptions, catcher), runnable));
}
public static final Thread createAndStartThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable)
{
return (Threading.createThread (context, configuration, runnable, true));
}
public static final Thread createDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, true), runnable));
}
public static final Thread createDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, true, exceptions, catcher), runnable));
}
public static final Thread createNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, false), runnable));
}
public static final Thread createNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, false, exceptions, catcher), runnable));
}
public static final Thread createThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable)
{
return (Threading.createThread (context, configuration, runnable, false));
}
public static final Thread createThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable, final boolean start)
{
Preconditions.checkNotNull (context);
Preconditions.checkNotNull (configuration);
Preconditions.checkNotNull (runnable);
final Thread thread = context.createThread (configuration, runnable);
if (start)
thread.start ();
return (thread);
}
public static final <_Object_ extends Object> _Object_ exchange (final Exchanger<_Object_> exchanger, final _Object_ sent)
{
return (Threading.exchange (exchanger, sent, -1));
}
public static final <_Object_ extends Object> _Object_ exchange (final Exchanger<_Object_> exchanger, final _Object_ sent, final long timeout)
{
Preconditions.checkNotNull (exchanger);
Preconditions.checkNotNull (sent);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final _Object_ received;
if (timeout >= 0)
received = exchanger.exchange (sent, timeout, TimeUnit.MILLISECONDS);
else if (timeout == -1)
received = exchanger.exchange (sent);
else
throw (new AssertionError ());
Preconditions.checkNotNull (received);
return (received);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
} catch (final TimeoutException exception) {
return (null);
}
}
public static final <_Outcome_ extends Object> _Outcome_ executeWithCurrentThreadClassLoader (final ClassLoader classLoader, final Callable<_Outcome_> operation)
throws Exception
{
final ClassLoader originalClassLoader = Threading.getCurrentThreadClassLoader ();
Threading.setCurrentThreadClassLoader (classLoader);
try {
return (operation.call ());
} finally {
Threading.setCurrentThreadClassLoader (originalClassLoader);
}
}
public static final void exit ()
{
Threading.exit (Threading.defaultAbortExitCode);
}
public static final void exit (final int exitCode)
{
final int finalExitCode;
if ((exitCode >= 0) && (exitCode <= 255))
finalExitCode = exitCode;
else
finalExitCode = Threading.defaultAbortExitCode;
Runtime.getRuntime ().exit (finalExitCode);
Threading.loop ();
}
public static final ThreadingContext getCurrentContext ()
{
return (CurrentContext.instance.get ());
}
public static final Thread getCurrentThread ()
{
return (Thread.currentThread ());
}
public static final ClassLoader getCurrentThreadClassLoader ()
{
return (Threading.getCurrentThread ().getContextClassLoader ());
}
public static final ThreadGroup getCurrentThreadGroup ()
{
return (Thread.currentThread ().getThreadGroup ());
}
@Deprecated
public static final ThreadingContext getDefaultContext ()
{
final ThreadingContext context = Threading.defaultContext.get ();
Preconditions.checkState (context != null);
return (context);
}
public static final ThreadGroup getRootThreadGroup ()
{
final ThreadGroup root;
for (ThreadGroup child = Thread.currentThread ().getThreadGroup (), parent = child.getParent (); true; child = parent, parent = child.getParent ())
if (parent == null) {
root = child;
break;
}
return (root);
}
public static final void halt ()
{
Threading.halt (Threading.defaultHaltExitCode);
}
public static final void halt (final int exitCode)
{
final int finalExitCode;
if ((exitCode >= 0) && (exitCode <= 255))
finalExitCode = exitCode;
else
finalExitCode = Threading.defaultHaltExitCode;
Runtime.getRuntime ().halt (finalExitCode);
Threading.loop ();
}
public static final void interrupt (final Iterable<? extends Thread> threads)
{
Preconditions.checkNotNull (threads);
for (final Thread thread : threads)
Threading.interrupt (thread);
}
public static final void interrupt (final Thread thread)
{
Preconditions.checkNotNull (thread);
thread.interrupt ();
}
public static final void interruptCurrentThread ()
{
Threading.interrupt (Threading.getCurrentThread ());
}
public static final boolean isCurrentContext (final ThreadingContext context)
{
return (context == Threading.getCurrentContext ());
}
public static final boolean isCurrentThread (final Thread thread)
{
Preconditions.checkNotNull (thread);
return (thread == Threading.getCurrentThread ());
}
public static final boolean isCurrentThreadGroup (final ThreadGroup group)
{
Preconditions.checkNotNull (group);
return (group == Threading.getCurrentThreadGroup ());
}
public static final boolean isCurrentThreadInterrupted ()
{
return (Threading.getCurrentThread ().isInterrupted ());
}
public static final boolean join (final ExecutorService executor)
{
return (Threading.join (executor, -1));
}
public static final boolean join (final ExecutorService executor, final long timeout)
{
Preconditions.checkNotNull (executor);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long timeoutAmount = (timeout >= 0) ? timeout : Long.MAX_VALUE;
final TimeUnit timeoutUnit = (timeout >= 0) ? TimeUnit.MILLISECONDS : TimeUnit.DAYS;
return (executor.awaitTermination (timeoutAmount, timeoutUnit));
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Iterable<? extends Thread> threads)
{
return (Threading.join (threads, -1));
}
public static final boolean join (final Iterable<? extends Thread> threads, final long timeout)
{
// NOTE: Mirrors the code from `java.lang.Thread.join(long)`.
Preconditions.checkNotNull (threads);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long begin = System.currentTimeMillis ();
for (final Thread thread : threads) {
Preconditions.checkNotNull (thread);
final long remainingTimeout;
if (timeout > 0) {
remainingTimeout = timeout - (System.currentTimeMillis () - begin);
if (remainingTimeout <= 0)
return (false);
} else if (timeout == 0)
remainingTimeout = 1;
else if (timeout == -1)
remainingTimeout = -1;
else
throw (new AssertionError ());
if (remainingTimeout > 0)
thread.join (remainingTimeout);
else if (remainingTimeout == -1)
thread.join ();
else
throw (new AssertionError ());
}
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Process process)
{
Preconditions.checkNotNull (process);
try {
process.waitFor ();
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Thread thread)
{
return (Threading.join (thread, -1));
}
public static final boolean join (final Thread thread, final long timeout)
{
Preconditions.checkNotNull (thread);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long remainingTimeout;
if (timeout > 0)
remainingTimeout = timeout;
else if (timeout == 0)
remainingTimeout = 1;
else if (timeout == -1)
remainingTimeout = -1;
else
throw (new AssertionError ());
if (remainingTimeout > 0)
thread.join (remainingTimeout);
else if (remainingTimeout == -1)
thread.join ();
else
throw (new AssertionError ());
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean lock (final Lock lock)
{
return (Threading.lock (lock, -1));
}
public static final boolean lock (final Lock lock, final long timeout)
{
Preconditions.checkNotNull (lock);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (lock.tryLock (timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (lock.tryLock ());
else if (timeout == -1) {
lock.lockInterruptibly ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final void notify (final Object monitor)
{
Preconditions.checkNotNull (monitor);
synchronized (monitor) {
monitor.notify ();
}
}
public static final void notifyAll (final Object monitor)
{
Preconditions.checkNotNull (monitor);
synchronized (monitor) {
monitor.notifyAll ();
}
}
public static final <_Object_ extends Object> boolean offer (final BlockingQueue<_Object_> queue, final _Object_ object)
{
return (Threading.offer (queue, object, -1));
}
public static final <_Object_ extends Object> boolean offer (final BlockingQueue<_Object_> queue, final _Object_ object, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkNotNull (object);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.offer (object, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.offer (object));
else if (timeout == -1) {
queue.put (object);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final <_Object_ extends Object> _Object_ poll (final BlockingQueue<_Object_> queue)
{
return (Threading.poll (queue, -1));
}
public static final <_Object_ extends Object> _Object_ poll (final BlockingQueue<_Object_> queue, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.poll (timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.poll ());
else if (timeout == -1)
return (queue.take ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
}
}
public static final void registerExitCallback (final ThreadingContext context, final Object owner, final String name, final Runnable runnable)
{
Preconditions.checkNotNull (context);
Preconditions.checkNotNull (owner);
Preconditions.checkNotNull (runnable);
Runtime.getRuntime ().addShutdownHook (context.createThread (ThreadConfiguration.create (owner, name, true), runnable));
}
public static final <_Object_ extends Object> Reference<? extends _Object_> remove (final ReferenceQueue<_Object_> queue)
{
return (Threading.remove (queue, -1));
}
public static final <_Object_ extends Object> Reference<? extends _Object_> remove (final ReferenceQueue<_Object_> queue, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.remove (timeout));
else if (timeout == 0)
return (queue.remove (1));
else if (timeout == -1)
return (queue.remove ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
}
}
public static final void setCurrentThreadClassLoader (final ClassLoader classLoader)
{
Preconditions.checkNotNull (classLoader);
Threading.getCurrentThread ().setContextClassLoader (classLoader);
}
public static final void setDefaultContext (final ThreadingContext context)
{
Threading.defaultContext.set (context);
}
public static final boolean sleep (final long timeout)
{
try {
Thread.sleep (timeout);
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final int start (final Iterable<? extends Thread> threads)
{
Preconditions.checkNotNull (threads);
int count = 0;
for (final Thread thread : threads) {
Preconditions.checkNotNull (thread);
try {
thread.start ();
count++;
} catch (final IllegalThreadStateException exception) {
// NOTE: intentional
}
}
return (count);
}
public static final <_Object_ extends Object> boolean transfer (final TransferQueue<_Object_> queue, final _Object_ object)
{
return (Threading.transfer (queue, object, -1));
}
public static final <_Object_ extends Object> boolean transfer (final TransferQueue<_Object_> queue, final _Object_ object, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkNotNull (object);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.tryTransfer (object, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.tryTransfer (object));
else if (timeout == -1) {
queue.transfer (object);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean wait (final Object monitor)
{
return (Threading.wait (monitor, -1));
}
public static final boolean wait (final Object monitor, final long timeout)
{
Preconditions.checkNotNull (monitor);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
synchronized (monitor) {
if (timeout > 0)
monitor.wait (timeout);
else if (timeout == 0)
monitor.wait (1);
else if (timeout == -1)
monitor.wait ();
else
throw (new AssertionError ());
}
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
private static final void loop ()
{
while (true) {
final Object object = new Object ();
synchronized (object) {
try {
object.wait ();
} catch (final InterruptedException exception) {
// NOTE: intentional
}
}
}
}
public static final int defaultAbortExitCode = AbortingExceptionTracer.defaultExitCode;
public static final int defaultHaltExitCode = AbortingExceptionTracer.defaultExitCode;
private static final AtomicReference<ThreadingContext> defaultContext = Atomics.newReference (null);
private static final class CurrentContext
extends ThreadLocal<ThreadingContext>
{
private CurrentContext ()
{
super ();
this.initialValueActive = false;
}
@Override
public final ThreadingContext get ()
{
synchronized (this) {
if (this.initialValueActive)
return (null);
return (super.get ());
}
}
@Override
public final void remove ()
{
throw (new UnsupportedOperationException ());
}
@Override
public final void set (final ThreadingContext value)
{
throw (new UnsupportedOperationException ());
}
@Override
protected final ThreadingContext initialValue ()
{
synchronized (this) {
try {
this.initialValueActive = true;
ThreadingContext context = super.initialValue ();
final Thread thread = Thread.currentThread ();
if (context == null) {
if (thread instanceof ManagedThread) {
context = ((ManagedThread) thread).getContext ();
Preconditions.checkNotNull (context);
}
}
if (context == null) {
for (ThreadGroup group = thread.getThreadGroup (); group != null; group = group.getParent ())
if (group instanceof ManagedThreadGroup) {
context = ((ManagedThreadGroup) group).getContext ();
Preconditions.checkNotNull (context);
break;
}
}
if (context != null) {
if (!context.isManaged (thread))
context.registerThread (thread);
}
return (context);
} finally {
this.initialValueActive = false;
}
}
}
private boolean initialValueActive;
public static final CurrentContext instance = new CurrentContext ();
}
}
| tools-threading/src/main/java/eu/mosaic_cloud/tools/threading/tools/Threading.java | /*
* #%L
* mosaic-tools-threading
* %%
* Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania)
* %%
* 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%
*/
// $codepro.audit.disable emptyCatchClause
// $codepro.audit.disable logExceptions
package eu.mosaic_cloud.tools.threading.tools;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import eu.mosaic_cloud.tools.exceptions.core.ExceptionTracer;
import eu.mosaic_cloud.tools.exceptions.tools.AbortingExceptionTracer;
import eu.mosaic_cloud.tools.threading.core.ThreadConfiguration;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext.ManagedThread;
import eu.mosaic_cloud.tools.threading.core.ThreadingContext.ManagedThreadGroup;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Atomics;
public final class Threading
extends Object
{
private Threading ()
{
super ();
throw (new UnsupportedOperationException ());
}
public static final boolean acquire (final Semaphore semaphore)
{
return (Threading.acquire (semaphore, 1));
}
public static final boolean acquire (final Semaphore semaphore, final int tokens)
{
return (Threading.acquire (semaphore, tokens, -1));
}
public static final boolean acquire (final Semaphore semaphore, final int tokens, final long timeout)
{
Preconditions.checkNotNull (semaphore);
Preconditions.checkArgument (tokens >= 0);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (semaphore.tryAcquire (tokens, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (semaphore.tryAcquire ());
else if (timeout == -1) {
semaphore.acquire (tokens);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean acquire (final Semaphore semaphore, final long timeout)
{
return (Threading.acquire (semaphore, 1, timeout));
}
public static final boolean await (final Condition condition)
{
return (Threading.await (condition, -1));
}
public static final boolean await (final Condition condition, final long timeout)
{
Preconditions.checkNotNull (condition);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (condition.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1) {
condition.await ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean await (final CountDownLatch latch)
{
return (Threading.await (latch, -1));
}
public static final boolean await (final CountDownLatch latch, final long timeout)
{
Preconditions.checkNotNull (latch);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (latch.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1) {
latch.await ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final int await (final CyclicBarrier barrier)
{
return (Threading.await (barrier, -1));
}
public static final int await (final CyclicBarrier barrier, final long timeout)
{
Preconditions.checkNotNull (barrier);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout >= 0)
return (barrier.await (timeout, TimeUnit.MILLISECONDS));
else if (timeout == -1)
return (barrier.await ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (-1);
} catch (final TimeoutException exception) {
return (-1);
} catch (final BrokenBarrierException exception) {
return (-1);
}
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future)
throws ExecutionException
{
return (Threading.await (future, null));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final _Object_ timeoutMarker)
throws ExecutionException
{
return (Threading.await (future, -1, timeoutMarker));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final long timeout)
throws ExecutionException
{
return (Threading.await (future, timeout, null));
}
public static final <_Object_ extends Object> _Object_ await (final Future<_Object_> future, final long timeout, final _Object_ timeoutMarker)
throws ExecutionException
{
Preconditions.checkNotNull (future);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final _Object_ received;
if (timeout >= 0)
received = future.get (timeout, TimeUnit.MILLISECONDS);
else if (timeout == -1)
received = future.get ();
else
throw (new AssertionError ());
return (received);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (timeoutMarker);
} catch (final TimeoutException exception) {
return (timeoutMarker);
}
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future)
{
return (Threading.awaitOrCatch (future, null, null));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final _Object_ timeoutMarker, final _Object_ exceptionMarker)
{
return (Threading.awaitOrCatch (future, -1, timeoutMarker, exceptionMarker));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final long timeout)
{
return (Threading.awaitOrCatch (future, timeout, null, null));
}
public static final <_Object_ extends Object> _Object_ awaitOrCatch (final Future<_Object_> future, final long timeout, final _Object_ timeoutMarker, final _Object_ exceptionMarker)
{
try {
return (Threading.await (future, timeout, timeoutMarker));
} catch (final ExecutionException exception) {
return (exceptionMarker);
}
}
public static final Thread createAndStartDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, true), runnable));
}
public static final Thread createAndStartDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, true, exceptions, catcher), runnable));
}
public static final Thread createAndStartNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, false), runnable));
}
public static final Thread createAndStartNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createAndStartThread (threading, ThreadConfiguration.create (owner, name, false, exceptions, catcher), runnable));
}
public static final Thread createAndStartThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable)
{
return (Threading.createThread (context, configuration, runnable, true));
}
public static final Thread createDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, true), runnable));
}
public static final Thread createDaemonThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, true, exceptions, catcher), runnable));
}
public static final Thread createNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, false), runnable));
}
public static final Thread createNormalThread (final ThreadingContext threading, final Object owner, final String name, final Runnable runnable, final ExceptionTracer exceptions, final UncaughtExceptionHandler catcher)
{
return (Threading.createThread (threading, ThreadConfiguration.create (owner, name, false, exceptions, catcher), runnable));
}
public static final Thread createThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable)
{
return (Threading.createThread (context, configuration, runnable, false));
}
public static final Thread createThread (final ThreadingContext context, final ThreadConfiguration configuration, final Runnable runnable, final boolean start)
{
Preconditions.checkNotNull (context);
Preconditions.checkNotNull (configuration);
Preconditions.checkNotNull (runnable);
final Thread thread = context.createThread (configuration, runnable);
if (start)
thread.start ();
return (thread);
}
public static final <_Object_ extends Object> _Object_ exchange (final Exchanger<_Object_> exchanger, final _Object_ sent)
{
return (Threading.exchange (exchanger, sent, -1));
}
public static final <_Object_ extends Object> _Object_ exchange (final Exchanger<_Object_> exchanger, final _Object_ sent, final long timeout)
{
Preconditions.checkNotNull (exchanger);
Preconditions.checkNotNull (sent);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final _Object_ received;
if (timeout >= 0)
received = exchanger.exchange (sent, timeout, TimeUnit.MILLISECONDS);
else if (timeout == -1)
received = exchanger.exchange (sent);
else
throw (new AssertionError ());
Preconditions.checkNotNull (received);
return (received);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
} catch (final TimeoutException exception) {
return (null);
}
}
public static final void exit ()
{
Threading.exit (Threading.defaultAbortExitCode);
}
public static final void exit (final int exitCode)
{
final int finalExitCode;
if ((exitCode >= 0) && (exitCode <= 255))
finalExitCode = exitCode;
else
finalExitCode = Threading.defaultAbortExitCode;
Runtime.getRuntime ().exit (finalExitCode);
Threading.loop ();
}
public static final ThreadingContext getCurrentContext ()
{
return (CurrentContext.instance.get ());
}
public static final Thread getCurrentThread ()
{
return (Thread.currentThread ());
}
public static final ThreadGroup getCurrentThreadGroup ()
{
return (Thread.currentThread ().getThreadGroup ());
}
@Deprecated
public static final ThreadingContext getDefaultContext ()
{
final ThreadingContext context = Threading.defaultContext.get ();
Preconditions.checkState (context != null);
return (context);
}
public static final ThreadGroup getRootThreadGroup ()
{
final ThreadGroup root;
for (ThreadGroup child = Thread.currentThread ().getThreadGroup (), parent = child.getParent (); true; child = parent, parent = child.getParent ())
if (parent == null) {
root = child;
break;
}
return (root);
}
public static final void halt ()
{
Threading.halt (Threading.defaultHaltExitCode);
}
public static final void halt (final int exitCode)
{
final int finalExitCode;
if ((exitCode >= 0) && (exitCode <= 255))
finalExitCode = exitCode;
else
finalExitCode = Threading.defaultHaltExitCode;
Runtime.getRuntime ().halt (finalExitCode);
Threading.loop ();
}
public static final void interrupt (final Iterable<? extends Thread> threads)
{
Preconditions.checkNotNull (threads);
for (final Thread thread : threads)
Threading.interrupt (thread);
}
public static final void interrupt (final Thread thread)
{
Preconditions.checkNotNull (thread);
thread.interrupt ();
}
public static final void interruptCurrentThread ()
{
Threading.interrupt (Threading.getCurrentThread ());
}
public static final boolean isCurrentContext (final ThreadingContext context)
{
return (context == Threading.getCurrentContext ());
}
public static final boolean isCurrentThread (final Thread thread)
{
Preconditions.checkNotNull (thread);
return (thread == Threading.getCurrentThread ());
}
public static final boolean isCurrentThreadGroup (final ThreadGroup group)
{
Preconditions.checkNotNull (group);
return (group == Threading.getCurrentThreadGroup ());
}
public static final boolean isCurrentThreadInterrupted ()
{
return (Threading.getCurrentThread ().isInterrupted ());
}
public static final boolean join (final ExecutorService executor)
{
return (Threading.join (executor, -1));
}
public static final boolean join (final ExecutorService executor, final long timeout)
{
Preconditions.checkNotNull (executor);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long timeoutAmount = (timeout >= 0) ? timeout : Long.MAX_VALUE;
final TimeUnit timeoutUnit = (timeout >= 0) ? TimeUnit.MILLISECONDS : TimeUnit.DAYS;
return (executor.awaitTermination (timeoutAmount, timeoutUnit));
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Iterable<? extends Thread> threads)
{
return (Threading.join (threads, -1));
}
public static final boolean join (final Iterable<? extends Thread> threads, final long timeout)
{
// NOTE: Mirrors the code from `java.lang.Thread.join(long)`.
Preconditions.checkNotNull (threads);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long begin = System.currentTimeMillis ();
for (final Thread thread : threads) {
Preconditions.checkNotNull (thread);
final long remainingTimeout;
if (timeout > 0) {
remainingTimeout = timeout - (System.currentTimeMillis () - begin);
if (remainingTimeout <= 0)
return (false);
} else if (timeout == 0)
remainingTimeout = 1;
else if (timeout == -1)
remainingTimeout = -1;
else
throw (new AssertionError ());
if (remainingTimeout > 0)
thread.join (remainingTimeout);
else if (remainingTimeout == -1)
thread.join ();
else
throw (new AssertionError ());
}
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Process process)
{
Preconditions.checkNotNull (process);
try {
process.waitFor ();
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean join (final Thread thread)
{
return (Threading.join (thread, -1));
}
public static final boolean join (final Thread thread, final long timeout)
{
Preconditions.checkNotNull (thread);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
final long remainingTimeout;
if (timeout > 0)
remainingTimeout = timeout;
else if (timeout == 0)
remainingTimeout = 1;
else if (timeout == -1)
remainingTimeout = -1;
else
throw (new AssertionError ());
if (remainingTimeout > 0)
thread.join (remainingTimeout);
else if (remainingTimeout == -1)
thread.join ();
else
throw (new AssertionError ());
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean lock (final Lock lock)
{
return (Threading.lock (lock, -1));
}
public static final boolean lock (final Lock lock, final long timeout)
{
Preconditions.checkNotNull (lock);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (lock.tryLock (timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (lock.tryLock ());
else if (timeout == -1) {
lock.lockInterruptibly ();
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final void notify (final Object monitor)
{
Preconditions.checkNotNull (monitor);
synchronized (monitor) {
monitor.notify ();
}
}
public static final void notifyAll (final Object monitor)
{
Preconditions.checkNotNull (monitor);
synchronized (monitor) {
monitor.notifyAll ();
}
}
public static final <_Object_ extends Object> boolean offer (final BlockingQueue<_Object_> queue, final _Object_ object)
{
return (Threading.offer (queue, object, -1));
}
public static final <_Object_ extends Object> boolean offer (final BlockingQueue<_Object_> queue, final _Object_ object, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkNotNull (object);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.offer (object, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.offer (object));
else if (timeout == -1) {
queue.put (object);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final <_Object_ extends Object> _Object_ poll (final BlockingQueue<_Object_> queue)
{
return (Threading.poll (queue, -1));
}
public static final <_Object_ extends Object> _Object_ poll (final BlockingQueue<_Object_> queue, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.poll (timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.poll ());
else if (timeout == -1)
return (queue.take ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
}
}
public static final void registerExitCallback (final ThreadingContext context, final Object owner, final String name, final Runnable runnable)
{
Preconditions.checkNotNull (context);
Preconditions.checkNotNull (owner);
Preconditions.checkNotNull (runnable);
Runtime.getRuntime ().addShutdownHook (context.createThread (ThreadConfiguration.create (owner, name, true), runnable));
}
public static final <_Object_ extends Object> Reference<? extends _Object_> remove (final ReferenceQueue<_Object_> queue)
{
return (Threading.remove (queue, -1));
}
public static final <_Object_ extends Object> Reference<? extends _Object_> remove (final ReferenceQueue<_Object_> queue, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.remove (timeout));
else if (timeout == 0)
return (queue.remove (1));
else if (timeout == -1)
return (queue.remove ());
else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (null);
}
}
public static final void setDefaultContext (final ThreadingContext context)
{
Threading.defaultContext.set (context);
}
public static final boolean sleep (final long timeout)
{
try {
Thread.sleep (timeout);
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final int start (final Iterable<? extends Thread> threads)
{
Preconditions.checkNotNull (threads);
int count = 0;
for (final Thread thread : threads) {
Preconditions.checkNotNull (thread);
try {
thread.start ();
count++;
} catch (final IllegalThreadStateException exception) {
// NOTE: intentional
}
}
return (count);
}
public static final <_Object_ extends Object> boolean transfer (final TransferQueue<_Object_> queue, final _Object_ object)
{
return (Threading.transfer (queue, object, -1));
}
public static final <_Object_ extends Object> boolean transfer (final TransferQueue<_Object_> queue, final _Object_ object, final long timeout)
{
Preconditions.checkNotNull (queue);
Preconditions.checkNotNull (object);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
if (timeout > 0)
return (queue.tryTransfer (object, timeout, TimeUnit.MILLISECONDS));
else if (timeout == 0)
return (queue.tryTransfer (object));
else if (timeout == -1) {
queue.transfer (object);
return (true);
} else
throw (new AssertionError ());
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
public static final boolean wait (final Object monitor)
{
return (Threading.wait (monitor, -1));
}
public static final boolean wait (final Object monitor, final long timeout)
{
Preconditions.checkNotNull (monitor);
Preconditions.checkArgument ((timeout >= 0) || (timeout == -1));
try {
synchronized (monitor) {
if (timeout > 0)
monitor.wait (timeout);
else if (timeout == 0)
monitor.wait (1);
else if (timeout == -1)
monitor.wait ();
else
throw (new AssertionError ());
}
return (true);
} catch (final InterruptedException exception) {
Threading.interruptCurrentThread ();
return (false);
}
}
private static final void loop ()
{
while (true) {
final Object object = new Object ();
synchronized (object) {
try {
object.wait ();
} catch (final InterruptedException exception) {
// NOTE: intentional
}
}
}
}
public static final int defaultAbortExitCode = AbortingExceptionTracer.defaultExitCode;
public static final int defaultHaltExitCode = AbortingExceptionTracer.defaultExitCode;
private static final AtomicReference<ThreadingContext> defaultContext = Atomics.newReference (null);
private static final class CurrentContext
extends ThreadLocal<ThreadingContext>
{
private CurrentContext ()
{
super ();
this.initialValueActive = false;
}
@Override
public final ThreadingContext get ()
{
synchronized (this) {
if (this.initialValueActive)
return (null);
return (super.get ());
}
}
@Override
public final void remove ()
{
throw (new UnsupportedOperationException ());
}
@Override
public final void set (final ThreadingContext value)
{
throw (new UnsupportedOperationException ());
}
@Override
protected final ThreadingContext initialValue ()
{
synchronized (this) {
try {
this.initialValueActive = true;
ThreadingContext context = super.initialValue ();
final Thread thread = Thread.currentThread ();
if (context == null) {
if (thread instanceof ManagedThread) {
context = ((ManagedThread) thread).getContext ();
Preconditions.checkNotNull (context);
}
}
if (context == null) {
for (ThreadGroup group = thread.getThreadGroup (); group != null; group = group.getParent ())
if (group instanceof ManagedThreadGroup) {
context = ((ManagedThreadGroup) group).getContext ();
Preconditions.checkNotNull (context);
break;
}
}
if (context != null) {
if (!context.isManaged (thread))
context.registerThread (thread);
}
return (context);
} finally {
this.initialValueActive = false;
}
}
}
private boolean initialValueActive;
public static final CurrentContext instance = new CurrentContext ();
}
}
| Add support for current thread context class-loader manipulation
| tools-threading/src/main/java/eu/mosaic_cloud/tools/threading/tools/Threading.java | Add support for current thread context class-loader manipulation | <ide><path>ools-threading/src/main/java/eu/mosaic_cloud/tools/threading/tools/Threading.java
<ide> import java.lang.ref.ReferenceQueue;
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.BrokenBarrierException;
<add>import java.util.concurrent.Callable;
<ide> import java.util.concurrent.CountDownLatch;
<ide> import java.util.concurrent.CyclicBarrier;
<ide> import java.util.concurrent.Exchanger;
<ide> }
<ide> }
<ide>
<add> public static final <_Outcome_ extends Object> _Outcome_ executeWithCurrentThreadClassLoader (final ClassLoader classLoader, final Callable<_Outcome_> operation)
<add> throws Exception
<add> {
<add> final ClassLoader originalClassLoader = Threading.getCurrentThreadClassLoader ();
<add> Threading.setCurrentThreadClassLoader (classLoader);
<add> try {
<add> return (operation.call ());
<add> } finally {
<add> Threading.setCurrentThreadClassLoader (originalClassLoader);
<add> }
<add> }
<add>
<ide> public static final void exit ()
<ide> {
<ide> Threading.exit (Threading.defaultAbortExitCode);
<ide> public static final Thread getCurrentThread ()
<ide> {
<ide> return (Thread.currentThread ());
<add> }
<add>
<add> public static final ClassLoader getCurrentThreadClassLoader ()
<add> {
<add> return (Threading.getCurrentThread ().getContextClassLoader ());
<ide> }
<ide>
<ide> public static final ThreadGroup getCurrentThreadGroup ()
<ide> Threading.interruptCurrentThread ();
<ide> return (null);
<ide> }
<add> }
<add>
<add> public static final void setCurrentThreadClassLoader (final ClassLoader classLoader)
<add> {
<add> Preconditions.checkNotNull (classLoader);
<add> Threading.getCurrentThread ().setContextClassLoader (classLoader);
<ide> }
<ide>
<ide> public static final void setDefaultContext (final ThreadingContext context) |
|
Java | apache-2.0 | 2a6dab5eea12176dce3f7a1bdfc67de1f05e36ad | 0 | saki4510t/libcommon,saki4510t/libcommon | package com.serenegiant.glutils;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Surface;
import com.serenegiant.graphics.BitmapHelper;
import com.serenegiant.system.BuildCheck;
import com.serenegiant.utils.Pool;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import androidx.annotation.WorkerThread;
import static com.serenegiant.glutils.GLConst.GL_TEXTURE_EXTERNAL_OES;
/**
* Surface/SurfaceTextureに描画された内容をビットマップとして取得するためのヘルパークラス
* ImageReaderをイメージして似た使い方ができるようにしてみた
*/
public class SurfaceReader {
private static final boolean DEBUG = false;
private static final String TAG = SurfaceReader.class.getSimpleName();
public interface OnImageAvailableListener {
public void onImageAvailable(@NonNull final SurfaceReader reader);
}
private static final int REQUEST_DRAW = 1;
private static final int REQUEST_RECREATE_MASTER_SURFACE = 5;
@NonNull
private final Object mSync = new Object();
@NonNull
private final Object mReleaseLock = new Object();
private final int mWidth;
private final int mHeight;
@NonNull
private final Bitmap.Config mConfig;
private final int mMaxImages;
@NonNull
private final Pool<Bitmap> mPool;
@NonNull
private final LinkedBlockingDeque<Bitmap> mQueue = new LinkedBlockingDeque<>();
@NonNull
private final EglTask mEglTask;
@Nullable
private OnImageAvailableListener mListener;
@Nullable
private Handler mListenerHandler;
@NonNull
private final Paint mPaint = new Paint();
@Size(min=16)
@NonNull
final float[] mTexMatrix = new float[16];
@NonNull
private final ByteBuffer mWorkBuffer;
private int mTexId;
private SurfaceTexture mInputTexture;
private Surface mInputSurface;
private GLDrawer2D mDrawer;
private boolean mIsReaderValid = false;
private volatile boolean mAllBitmapAcquired = false;
/**
* コンストラクタ
* @param width
* @param height
* @param config 取得するビットマップのConfig
* @param maxImages 同時に取得できるビットマップの最大数
*/
public SurfaceReader(
@IntRange(from = 1) final int width, @IntRange(from = 1) final int height,
@NonNull final Bitmap.Config config, final int maxImages) {
mWidth = width;
mHeight = height;
mConfig = config;
mMaxImages = maxImages;
mPool = new Pool<Bitmap>(1, mMaxImages) {
@NonNull
@Override
protected Bitmap createObject(@Nullable final Object... args) {
return Bitmap.createBitmap(width, height, config);
}
};
final Semaphore sem = new Semaphore(0);
mEglTask = new EglTask(GLUtils.getSupportedGLVersion(),
null, 0,
width, height) {
@Override
protected void onStart() {
handleOnStart();
}
@Override
protected void onStop() {
handleOnStop();
}
@Override
protected Object processRequest(final int request,
final int arg1, final int arg2, final Object obj)
throws TaskBreak {
if (DEBUG) Log.v(TAG, "processRequest:");
final Object result = handleRequest(request, arg1, arg2, obj);
if ((request == REQUEST_RECREATE_MASTER_SURFACE)
&& (sem.availablePermits() == 0)) {
sem.release();
}
return result;
}
};
mWorkBuffer = ByteBuffer.allocateDirect(width * height * BitmapHelper.getPixelBytes(config));
new Thread(mEglTask, TAG).start();
if (!mEglTask.waitReady()) {
// 初期化に失敗した時
throw new RuntimeException("failed to start renderer thread");
}
mEglTask.offer(REQUEST_RECREATE_MASTER_SURFACE);
try {
final Surface surface;
synchronized (mSync) {
surface = mInputSurface;
}
if (surface == null) {
if (sem.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
mIsReaderValid = true;
} else {
throw new RuntimeException("failed to create surface");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
try {
release();
} finally {
super.finalize();
}
}
/**
* 関係するリソースを破棄する、再利用はできない
*/
public void release() {
if (DEBUG) Log.v(TAG, "release:");
setOnImageAvailableListener(null, null);
synchronized (mReleaseLock) {
mEglTask.release();
mIsReaderValid = false;
}
synchronized (mQueue) {
mQueue.clear();
}
mPool.clear();
}
/**
* 映像サイズ(幅)を取得
* @return
*/
public int getWidth() {
return mWidth;
}
/**
* 映像サイズ(高さ)を取得
* @return
*/
public int getHeight() {
return mHeight;
}
/**
* 取得するBitmapのConfigを取得
* @return
*/
@NonNull
public Bitmap.Config getConfig() {
return mConfig;
}
/**
* 同時に取得できる最大のビットマップの数を取得
* @return
*/
public int getMaxImages() {
return mMaxImages;
}
/**
* 映像受け取り用のSurfaceを取得
* 既に破棄されているなどしてsurfaceが取得できないときはIllegalStateExceptionを投げる
*
* @return
* @throws IllegalStateException
*/
@NonNull
public Surface getSurface() throws IllegalStateException {
synchronized (mSync) {
if (mInputSurface == null) {
throw new IllegalStateException("surface not ready, already released?");
}
return mInputSurface;
}
}
/**
* 読み取った映像データの準備ができたときのコールバックリスナーを登録
* @param listener
* @param handler
* @throws IllegalArgumentException
*/
public void setOnImageAvailableListener(
@Nullable final OnImageAvailableListener listener,
@Nullable final Handler handler) throws IllegalArgumentException {
synchronized (mSync) {
if (listener != null) {
Looper looper = handler != null ? handler.getLooper() : Looper.myLooper();
if (looper == null) {
throw new IllegalArgumentException(
"handler is null but the current thread is not a looper");
}
if (mListenerHandler == null || mListenerHandler.getLooper() != looper) {
mListenerHandler = new Handler(looper);
}
mListener = listener;
} else {
mListener = null;
mListenerHandler = null;
}
}
}
/**
* Bitmapを再利用可能にする
* @param bitmap
*/
public void recycle(@NonNull final Bitmap bitmap) {
mAllBitmapAcquired = false;
mPool.recycle(bitmap);
}
/**
* 最新のビットマップを取得する
* コンストラクタで指定した同時取得可能な最大のビットマップ数を超えて取得しようとするとIllegalStateExceptionを投げる
* ビットマップが準備できていなければnullを返す
* null以外が返ったときは#recycleでビットマップを返却して再利用可能にすること
* @return
* @throws IllegalStateException
*/
@Nullable
public Bitmap acquireLatestImage() throws IllegalStateException {
synchronized (mQueue) {
final Bitmap result = mQueue.pollLast();
while (!mQueue.isEmpty()) {
recycle(mQueue.pollFirst());
}
if (mAllBitmapAcquired && (result == null)) {
throw new IllegalStateException("all bitmap is acquired!");
}
return result;
}
}
/**
* 次のビットマップを取得する
* コンストラクタで指定した同時取得可能な最大のビットマップ数を超えて取得しようとするとIllegalStateExceptionを投げる
* ビットマップが準備できていなければnullを返す
* null以外が返ったときは#recycleでビットマップを返却して再利用可能にすること
* @return
* @throws IllegalStateException
*/
@Nullable
public Bitmap acquireNextImage() throws IllegalStateException {
synchronized (mQueue) {
final Bitmap result = mQueue.pollFirst();
if (mAllBitmapAcquired && (result == null)) {
throw new IllegalStateException("all bitmap is acquired!");
}
return result;
}
}
//--------------------------------------------------------------------------------
// ワーカースレッド上での処理
/**
* ワーカースレッド開始時の処理(ここはワーカースレッド上)
*/
@WorkerThread
protected final void handleOnStart() {
if (DEBUG) Log.v(TAG, "handleOnStart:");
// OESテクスチャを直接ハンドリングできないのでオフスクリーンへ描画して読み込む
mDrawer = GLDrawer2D.create( mEglTask.isOES3Supported(), true);
}
/**
* ワーカースレッド終了時の処理(ここはまだワーカースレッド上)
*/
@WorkerThread
protected final void handleOnStop() {
if (DEBUG) Log.v(TAG, "handleOnStop:");
if (mDrawer != null) {
mDrawer.release();
mDrawer = null;
}
handleReleaseInputSurface();
}
@WorkerThread
protected Object handleRequest(final int request,
final int arg1, final int arg2, final Object obj) {
switch (request) {
case REQUEST_DRAW:
handleDraw();
break;
case REQUEST_RECREATE_MASTER_SURFACE:
handleReCreateInputSurface();
break;
default:
if (DEBUG) Log.v(TAG, "handleRequest:" + request);
break;
}
return null;
}
private int drawCnt;
@WorkerThread
protected void handleDraw() {
if (DEBUG && ((++drawCnt % 100) == 0)) Log.v(TAG, "handleDraw:" + drawCnt);
mEglTask.removeRequest(REQUEST_DRAW);
try {
mEglTask.makeCurrent();
mInputTexture.updateTexImage();
mInputTexture.getTransformMatrix(mTexMatrix);
} catch (final Exception e) {
Log.e(TAG, "handleDraw:thread id =" + Thread.currentThread().getId(), e);
return;
}
final Bitmap bitmap = obtainBitmap();
if (bitmap != null) {
mAllBitmapAcquired = false;
// OESテクスチャをオフスクリーン(マスターサーフェース)へ描画
mDrawer.draw(GLES20.GL_TEXTURE0, mTexId, mTexMatrix, 0);
// オフスクリーンから読み取り
mWorkBuffer.clear();
GLUtils.glReadPixels(mWorkBuffer, mWidth, mHeight);
// Bitmapへ代入
mWorkBuffer.clear();
bitmap.copyPixelsFromBuffer(mWorkBuffer);
synchronized (mQueue) {
mQueue.addLast(bitmap);
}
synchronized (mSync) {
if (mListenerHandler != null) {
mListenerHandler.removeCallbacks(mOnImageAvailableTask);
mListenerHandler.post(mOnImageAvailableTask);
} else if (DEBUG) {
Log.w(TAG, "handleDraw: Unexpectedly listener handler is null!");
}
}
} else {
mAllBitmapAcquired = true;
if (DEBUG) Log.w(TAG, "handleDraw: failed to obtain bitmap from pool!");
}
}
private final Runnable mOnImageAvailableTask = new Runnable() {
@Override
public void run() {
synchronized (mSync) {
if (mListener != null) {
mListener.onImageAvailable(SurfaceReader.this);
}
}
}
};
/**
* 映像入力用SurfaceTexture/Surfaceを再生成する
*/
@SuppressLint("NewApi")
@WorkerThread
protected void handleReCreateInputSurface() {
if (DEBUG) Log.v(TAG, "handleReCreateInputSurface:");
synchronized (mSync) {
mEglTask.makeCurrent();
handleReleaseInputSurface();
mEglTask.makeCurrent();
mTexId = GLHelper.initTex(
GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE0, GLES20.GL_NEAREST);
mInputTexture = new SurfaceTexture(mTexId);
mInputSurface = new Surface(mInputTexture);
if (BuildCheck.isAndroid4_1()) {
// XXX getIntrinsicWidth/getIntrinsicHeightの代わりにmImageWidth/mImageHeightを使うべきかも?
mInputTexture.setDefaultBufferSize(mWidth, mHeight);
}
mInputTexture.setOnFrameAvailableListener(mOnFrameAvailableListener);
}
}
/**
* 映像入力用Surfaceを破棄する
*/
@SuppressLint("NewApi")
@WorkerThread
protected void handleReleaseInputSurface() {
if (DEBUG) Log.v(TAG, "handleReleaseInputSurface:");
synchronized (mSync) {
if (mInputSurface != null) {
try {
mInputSurface.release();
} catch (final Exception e) {
Log.w(TAG, e);
}
mInputSurface = null;
}
if (mInputTexture != null) {
try {
mInputTexture.release();
} catch (final Exception e) {
Log.w(TAG, e);
}
mInputTexture = null;
}
if (mTexId != 0) {
GLHelper.deleteTex(mTexId);
mTexId = 0;
}
}
}
@Nullable
private Bitmap obtainBitmap() {
Bitmap result = mPool.obtain();
if (result == null) {
// フレームプールが空の時はキューの一番古い物を取得する
synchronized (mQueue) {
result = mQueue.pollFirst();
}
}
return result;
}
private final SurfaceTexture.OnFrameAvailableListener
mOnFrameAvailableListener = new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(final SurfaceTexture surfaceTexture) {
// if (DEBUG) Log.v(TAG, "onFrameAvailable:");
mEglTask.offer(REQUEST_DRAW);
}
};
}
| common/src/main/java/com/serenegiant/glutils/SurfaceReader.java | package com.serenegiant.glutils;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Surface;
import com.serenegiant.graphics.BitmapHelper;
import com.serenegiant.system.BuildCheck;
import com.serenegiant.utils.Pool;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import androidx.annotation.WorkerThread;
import static com.serenegiant.glutils.GLConst.GL_TEXTURE_EXTERNAL_OES;
/**
* Surface/SurfaceTextureに描画された内容をビットマップとして取得するためのヘルパークラス
* ImageReaderをイメージして似た使い方ができるようにしてみた
*/
public class SurfaceReader {
private static final boolean DEBUG = false;
private static final String TAG = SurfaceReader.class.getSimpleName();
public interface OnImageAvailableListener {
public void onImageAvailable(@NonNull final SurfaceReader reader);
}
private static final int REQUEST_DRAW = 1;
private static final int REQUEST_RECREATE_MASTER_SURFACE = 5;
@NonNull
private final Object mSync = new Object();
@NonNull
private final Object mReleaseLock = new Object();
private final int mWidth;
private final int mHeight;
@NonNull
private final Bitmap.Config mConfig;
private final int mMaxImages;
@NonNull
private final Pool<Bitmap> mPool;
@NonNull
private final LinkedBlockingDeque<Bitmap> mQueue = new LinkedBlockingDeque<>();
@NonNull
private final EglTask mEglTask;
@Nullable
private OnImageAvailableListener mListener;
@Nullable
private Handler mListenerHandler;
@NonNull
private final Paint mPaint = new Paint();
@Size(min=16)
@NonNull
final float[] mTexMatrix = new float[16];
@NonNull
private final ByteBuffer mWorkBuffer;
private int mTexId;
private SurfaceTexture mInputTexture;
private Surface mInputSurface;
private GLDrawer2D mDrawer;
private boolean mIsReaderValid = false;
private volatile boolean mAllBitmapAcquired = false;
/**
* コンストラクタ
* @param width
* @param height
* @param config 取得するビットマップのConfig
* @param maxImages 同時に取得できるビットマップの最大数
*/
public SurfaceReader(
@IntRange(from = 1) final int width, @IntRange(from = 1) final int height,
@NonNull final Bitmap.Config config, final int maxImages) {
mWidth = width;
mHeight = height;
mConfig = config;
mMaxImages = maxImages;
mPool = new Pool<Bitmap>(1, mMaxImages) {
@NonNull
@Override
protected Bitmap createObject(@Nullable final Object... args) {
return Bitmap.createBitmap(width, height, config);
}
};
final Semaphore sem = new Semaphore(0);
mEglTask = new EglTask(GLUtils.getSupportedGLVersion(),
null, 0,
width, height) {
@Override
protected void onStart() {
handleOnStart();
}
@Override
protected void onStop() {
handleOnStop();
}
@Override
protected Object processRequest(final int request,
final int arg1, final int arg2, final Object obj)
throws TaskBreak {
if (DEBUG) Log.v(TAG, "processRequest:");
final Object result = handleRequest(request, arg1, arg2, obj);
if (request == REQUEST_RECREATE_MASTER_SURFACE) {
sem.release();
}
return result;
}
};
mWorkBuffer = ByteBuffer.allocateDirect(width * height * BitmapHelper.getPixelBytes(config));
new Thread(mEglTask, TAG).start();
if (!mEglTask.waitReady()) {
// 初期化に失敗した時
throw new RuntimeException("failed to start renderer thread");
}
mEglTask.offer(REQUEST_RECREATE_MASTER_SURFACE);
try {
final Surface surface;
synchronized (mSync) {
surface = mInputSurface;
}
if (surface == null) {
if (sem.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
mIsReaderValid = true;
} else {
throw new RuntimeException("failed to create surface");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
try {
release();
} finally {
super.finalize();
}
}
/**
* 関係するリソースを破棄する、再利用はできない
*/
public void release() {
if (DEBUG) Log.v(TAG, "release:");
setOnImageAvailableListener(null, null);
synchronized (mReleaseLock) {
mEglTask.release();
mIsReaderValid = false;
}
synchronized (mQueue) {
mQueue.clear();
}
mPool.clear();
}
/**
* 映像サイズ(幅)を取得
* @return
*/
public int getWidth() {
return mWidth;
}
/**
* 映像サイズ(高さ)を取得
* @return
*/
public int getHeight() {
return mHeight;
}
/**
* 取得するBitmapのConfigを取得
* @return
*/
@NonNull
public Bitmap.Config getConfig() {
return mConfig;
}
/**
* 同時に取得できる最大のビットマップの数を取得
* @return
*/
public int getMaxImages() {
return mMaxImages;
}
/**
* 映像受け取り用のSurfaceを取得
* 既に破棄されているなどしてsurfaceが取得できないときはIllegalStateExceptionを投げる
*
* @return
* @throws IllegalStateException
*/
@NonNull
public Surface getSurface() throws IllegalStateException {
synchronized (mSync) {
if (mInputSurface == null) {
throw new IllegalStateException("surface not ready, already released?");
}
return mInputSurface;
}
}
/**
* 読み取った映像データの準備ができたときのコールバックリスナーを登録
* @param listener
* @param handler
* @throws IllegalArgumentException
*/
public void setOnImageAvailableListener(
@Nullable final OnImageAvailableListener listener,
@Nullable final Handler handler) throws IllegalArgumentException {
synchronized (mSync) {
if (listener != null) {
Looper looper = handler != null ? handler.getLooper() : Looper.myLooper();
if (looper == null) {
throw new IllegalArgumentException(
"handler is null but the current thread is not a looper");
}
if (mListenerHandler == null || mListenerHandler.getLooper() != looper) {
mListenerHandler = new Handler(looper);
}
mListener = listener;
} else {
mListener = null;
mListenerHandler = null;
}
}
}
/**
* Bitmapを再利用可能にする
* @param bitmap
*/
public void recycle(@NonNull final Bitmap bitmap) {
mAllBitmapAcquired = false;
mPool.recycle(bitmap);
}
/**
* 最新のビットマップを取得する
* コンストラクタで指定した同時取得可能な最大のビットマップ数を超えて取得しようとするとIllegalStateExceptionを投げる
* ビットマップが準備できていなければnullを返す
* null以外が返ったときは#recycleでビットマップを返却して再利用可能にすること
* @return
* @throws IllegalStateException
*/
@Nullable
public Bitmap acquireLatestImage() throws IllegalStateException {
synchronized (mQueue) {
final Bitmap result = mQueue.pollLast();
while (!mQueue.isEmpty()) {
recycle(mQueue.pollFirst());
}
if (mAllBitmapAcquired && (result == null)) {
throw new IllegalStateException("all bitmap is acquired!");
}
return result;
}
}
/**
* 次のビットマップを取得する
* コンストラクタで指定した同時取得可能な最大のビットマップ数を超えて取得しようとするとIllegalStateExceptionを投げる
* ビットマップが準備できていなければnullを返す
* null以外が返ったときは#recycleでビットマップを返却して再利用可能にすること
* @return
* @throws IllegalStateException
*/
@Nullable
public Bitmap acquireNextImage() throws IllegalStateException {
synchronized (mQueue) {
final Bitmap result = mQueue.pollFirst();
if (mAllBitmapAcquired && (result == null)) {
throw new IllegalStateException("all bitmap is acquired!");
}
return result;
}
}
//--------------------------------------------------------------------------------
// ワーカースレッド上での処理
/**
* ワーカースレッド開始時の処理(ここはワーカースレッド上)
*/
@WorkerThread
protected final void handleOnStart() {
if (DEBUG) Log.v(TAG, "handleOnStart:");
// OESテクスチャを直接ハンドリングできないのでオフスクリーンへ描画して読み込む
mDrawer = GLDrawer2D.create( mEglTask.isOES3Supported(), true);
}
/**
* ワーカースレッド終了時の処理(ここはまだワーカースレッド上)
*/
@WorkerThread
protected final void handleOnStop() {
if (DEBUG) Log.v(TAG, "handleOnStop:");
if (mDrawer != null) {
mDrawer.release();
mDrawer = null;
}
handleReleaseInputSurface();
}
@WorkerThread
protected Object handleRequest(final int request,
final int arg1, final int arg2, final Object obj) {
switch (request) {
case REQUEST_DRAW:
handleDraw();
break;
case REQUEST_RECREATE_MASTER_SURFACE:
handleReCreateInputSurface();
break;
default:
if (DEBUG) Log.v(TAG, "handleRequest:" + request);
break;
}
return null;
}
private int drawCnt;
@WorkerThread
protected void handleDraw() {
if (DEBUG && ((++drawCnt % 100) == 0)) Log.v(TAG, "handleDraw:" + drawCnt);
mEglTask.removeRequest(REQUEST_DRAW);
try {
mEglTask.makeCurrent();
mInputTexture.updateTexImage();
mInputTexture.getTransformMatrix(mTexMatrix);
} catch (final Exception e) {
Log.e(TAG, "handleDraw:thread id =" + Thread.currentThread().getId(), e);
return;
}
final Bitmap bitmap = obtainBitmap();
if (bitmap != null) {
mAllBitmapAcquired = false;
// OESテクスチャをオフスクリーン(マスターサーフェース)へ描画
mDrawer.draw(GLES20.GL_TEXTURE0, mTexId, mTexMatrix, 0);
// オフスクリーンから読み取り
mWorkBuffer.clear();
GLUtils.glReadPixels(mWorkBuffer, mWidth, mHeight);
// Bitmapへ代入
mWorkBuffer.clear();
bitmap.copyPixelsFromBuffer(mWorkBuffer);
synchronized (mQueue) {
mQueue.addLast(bitmap);
}
synchronized (mSync) {
if (mListenerHandler != null) {
mListenerHandler.removeCallbacks(mOnImageAvailableTask);
mListenerHandler.post(mOnImageAvailableTask);
} else if (DEBUG) {
Log.w(TAG, "handleDraw: Unexpectedly listener handler is null!");
}
}
} else {
mAllBitmapAcquired = true;
if (DEBUG) Log.w(TAG, "handleDraw: failed to obtain bitmap from pool!");
}
}
private final Runnable mOnImageAvailableTask = new Runnable() {
@Override
public void run() {
synchronized (mSync) {
if (mListener != null) {
mListener.onImageAvailable(SurfaceReader.this);
}
}
}
};
/**
* 映像入力用SurfaceTexture/Surfaceを再生成する
*/
@SuppressLint("NewApi")
@WorkerThread
protected void handleReCreateInputSurface() {
if (DEBUG) Log.v(TAG, "handleReCreateInputSurface:");
synchronized (mSync) {
mEglTask.makeCurrent();
handleReleaseInputSurface();
mEglTask.makeCurrent();
mTexId = GLHelper.initTex(
GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE0, GLES20.GL_NEAREST);
mInputTexture = new SurfaceTexture(mTexId);
mInputSurface = new Surface(mInputTexture);
if (BuildCheck.isAndroid4_1()) {
// XXX getIntrinsicWidth/getIntrinsicHeightの代わりにmImageWidth/mImageHeightを使うべきかも?
mInputTexture.setDefaultBufferSize(mWidth, mHeight);
}
mInputTexture.setOnFrameAvailableListener(mOnFrameAvailableListener);
}
}
/**
* 映像入力用Surfaceを破棄する
*/
@SuppressLint("NewApi")
@WorkerThread
protected void handleReleaseInputSurface() {
if (DEBUG) Log.v(TAG, "handleReleaseInputSurface:");
synchronized (mSync) {
if (mInputSurface != null) {
try {
mInputSurface.release();
} catch (final Exception e) {
Log.w(TAG, e);
}
mInputSurface = null;
}
if (mInputTexture != null) {
try {
mInputTexture.release();
} catch (final Exception e) {
Log.w(TAG, e);
}
mInputTexture = null;
}
if (mTexId != 0) {
GLHelper.deleteTex(mTexId);
mTexId = 0;
}
}
}
@Nullable
private Bitmap obtainBitmap() {
Bitmap result = mPool.obtain();
if (result == null) {
// フレームプールが空の時はキューの一番古い物を取得する
synchronized (mQueue) {
result = mQueue.pollFirst();
}
}
return result;
}
private final SurfaceTexture.OnFrameAvailableListener
mOnFrameAvailableListener = new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(final SurfaceTexture surfaceTexture) {
// if (DEBUG) Log.v(TAG, "onFrameAvailable:");
mEglTask.offer(REQUEST_DRAW);
}
};
}
| 初回のREQUEST_RECREATE_MASTER_SURFACE要求時のみSemaphoreをreleaseするように変更
| common/src/main/java/com/serenegiant/glutils/SurfaceReader.java | 初回のREQUEST_RECREATE_MASTER_SURFACE要求時のみSemaphoreをreleaseするように変更 | <ide><path>ommon/src/main/java/com/serenegiant/glutils/SurfaceReader.java
<ide> throws TaskBreak {
<ide> if (DEBUG) Log.v(TAG, "processRequest:");
<ide> final Object result = handleRequest(request, arg1, arg2, obj);
<del> if (request == REQUEST_RECREATE_MASTER_SURFACE) {
<add> if ((request == REQUEST_RECREATE_MASTER_SURFACE)
<add> && (sem.availablePermits() == 0)) {
<ide> sem.release();
<ide> }
<ide> return result; |
|
Java | mit | 24059ff0a7e12e30126060b78b7725a6e67ccfba | 0 | darkwrat/2016-02-IOTA,Ustimov/2016-02-IOTA | package su.iota.backend.frontend;
import co.paralleluniverse.actors.behaviors.ProxyServerActor;
import co.paralleluniverse.fibers.SuspendExecution;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Server;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.testng.annotations.*;
import su.iota.backend.accounts.AccountService;
import su.iota.backend.accounts.impl.AccountServiceMapImpl;
import su.iota.backend.main.ApplicationBootstrapper;
import su.iota.backend.misc.ServiceUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import su.iota.backend.models.UserProfile;
import su.iota.backend.settings.SettingsService;
import su.iota.backend.settings.impl.SettingsServiceFixedImpl;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.apache.http.HttpStatus.*;
import static org.testng.Assert.*;
public class FunctionalTest extends ProxyServerActor {
public static final int SOCKET_TIMEOUT = 5000;
public static final int CONNECT_TIMEOUT = 5000;
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
private Server server;
private CloseableHttpClient client;
private String uriFormat;
public FunctionalTest() {
super(true);
}
@BeforeClass
public void setUpClass() throws Exception, SuspendExecution, MultiException {
final ServiceLocator serviceLocator = ApplicationBootstrapper.setupServiceLocator(
new FunctionalTestDependencyBinder()
);
ServiceUtils.setupServiceUtils(serviceLocator);
final SettingsService settingsService = serviceLocator.getService(SettingsService.class);
uriFormat = String.format("http://127.0.0.1:%s/%s%%s",
settingsService.getServerPortSetting(),
settingsService.getServerContextPathSetting());
server = serviceLocator.getService(ApplicationBootstrapper.class).setupServer();
server.start();
}
@AfterClass
public void tearDownClass() throws Exception, IOException {
server.stop();
ServiceUtils.teardownServiceUtils();
}
@BeforeMethod
public void setUp() throws Exception {
client = HttpClients.custom().setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.build()
).build();
}
@AfterMethod
public void tearDown() throws Exception {
client.close();
}
@Test
public void testSignUpAndSignIn() throws Exception {
checkSignOut();
checkIsNotSignedIn();
final UserProfile userProfile = new UserProfile();
userProfile.setLogin("maxim.galaganov");
userProfile.setPassword("tellmeonceagainthatwritingtestsisareallygoodpractice");
final long userId = checkSignUp(userProfile);
checkAutoSignIn(userId);
checkSignOut();
checkSignIn(userProfile);
checkRepeatedSignUp(userProfile);
checkUserProfile(userId, userProfile);
checkProfileNotExistentUser(2);
}
private void checkProfileNotExistentUser(long userId) throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/user/" + userId)), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertFalse(obj.get("__ok").getAsBoolean());
}
private void checkUserProfile(long userId, UserProfile userProfile) throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/user/" + userId)), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
assertTrue(obj.has("id"));
assertTrue(obj.get("id").getAsLong() == userId);
assertTrue(obj.has("login"));
assertTrue(obj.get("login").getAsString().equals(userProfile.getLogin()));
}
private void checkRepeatedSignUp(UserProfile userProfile) throws IOException {
final HttpPut signUpRequest = new HttpPut(getResourceUri("/user"));
signUpRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
final JsonElement response = client.execute(signUpRequest, httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertFalse(obj.get("__ok").getAsBoolean());
}
private void checkSignIn(UserProfile userProfile) throws IOException {
final HttpPut signInRequest = new HttpPut(getResourceUri("/session"));
signInRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
final JsonElement response = client.execute(signInRequest, httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
}
private void checkIsNotSignedIn() throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertFalse(obj.get("__ok").getAsBoolean());
}
private void checkSignOut() throws IOException {
final JsonElement response = client.execute(new HttpDelete(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
}
private long checkSignUp(UserProfile userProfile) throws IOException {
final HttpPut signUpRequest = new HttpPut(getResourceUri("/user"));
signUpRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
final JsonElement response = client.execute(signUpRequest, httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
assertTrue(obj.has("id"));
final long userId = obj.get("id").getAsLong();
assertTrue(userId > 0);
return userId;
}
private void checkAutoSignIn(long userId) throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
assertTrue(obj.has("id"));
assertEquals(obj.get("id").getAsLong(), userId);
}
private void assertHttpStatus(HttpResponse httpResponse, int statusCode) {
assertEquals(httpResponse.getStatusLine().getStatusCode(), statusCode);
}
private String getResourceUri(String resourcePart) {
return String.format(uriFormat, resourcePart);
}
private JsonElement jsonResponse(HttpResponse httpResponse) throws IOException {
return new JsonParser().parse(new InputStreamReader(httpResponse.getEntity().getContent()));
}
private static class FunctionalTestDependencyBinder extends AbstractBinder {
@Override
protected void configure() {
bind(AccountServiceMapImpl.class).to(AccountService.class).ranked(1000);
bind(SettingsServiceFixedImpl.class).to(SettingsService.class).ranked(1000);
}
}
} | src/test/java/su/iota/backend/frontend/FunctionalTest.java | package su.iota.backend.frontend;
import co.paralleluniverse.actors.behaviors.ProxyServerActor;
import co.paralleluniverse.fibers.SuspendExecution;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.server.Server;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.testng.annotations.*;
import su.iota.backend.accounts.AccountService;
import su.iota.backend.accounts.impl.AccountServiceMapImpl;
import su.iota.backend.main.ApplicationBootstrapper;
import su.iota.backend.misc.ServiceUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import su.iota.backend.models.UserProfile;
import su.iota.backend.settings.SettingsService;
import su.iota.backend.settings.impl.SettingsServiceFixedImpl;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.apache.http.HttpStatus.*;
import static org.testng.Assert.*;
public class FunctionalTest extends ProxyServerActor {
public static final int SOCKET_TIMEOUT = 5000;
public static final int CONNECT_TIMEOUT = 5000;
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
private Server server;
private CloseableHttpClient client;
private String uriFormat;
public FunctionalTest() {
super(true);
}
@BeforeClass
public void setUpClass() throws Exception, SuspendExecution, MultiException {
final ServiceLocator serviceLocator = ApplicationBootstrapper.setupServiceLocator(
new FunctionalTestDependencyBinder()
);
ServiceUtils.setupServiceUtils(serviceLocator);
final SettingsService settingsService = serviceLocator.getService(SettingsService.class);
uriFormat = String.format("http://127.0.0.1:%s/%s%%s",
settingsService.getServerPortSetting(),
settingsService.getServerContextPathSetting());
server = serviceLocator.getService(ApplicationBootstrapper.class).setupServer();
server.start();
}
@AfterClass
public void tearDownClass() throws Exception, IOException {
server.stop();
ServiceUtils.teardownServiceUtils();
}
@BeforeMethod
public void setUp() throws Exception {
client = HttpClients.custom().setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.build()
).build();
}
@AfterMethod
public void tearDown() throws Exception {
client.close();
}
@Test
public void testSignUpAndSignIn() throws Exception {
checkSignOut();
checkIsSignedIn();
final UserProfile userProfile = new UserProfile();
userProfile.setLogin("maxim.galaganov");
userProfile.setPassword("tellmeonceagainthatwritingtestsisareallygoodpractice");
final long userId = checkSignUp(userProfile);
checkAutoSignIn(userId);
checkSignOut();
checkSignIn(userProfile);
}
private void checkSignIn(UserProfile userProfile) throws IOException {
final HttpPut signInRequest = new HttpPut(getResourceUri("/session"));
signInRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
final JsonElement response = client.execute(signInRequest, httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
}
private void checkIsSignedIn() throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertFalse(obj.get("__ok").getAsBoolean());
}
private void checkSignOut() throws IOException {
final JsonElement response = client.execute(new HttpDelete(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
}
private long checkSignUp(UserProfile userProfile) throws IOException {
final HttpPut signUpRequest = new HttpPut(getResourceUri("/user"));
signUpRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
final JsonElement response = client.execute(signUpRequest, httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
assertTrue(obj.has("id"));
final long userId = obj.get("id").getAsLong();
assertTrue(userId > 0);
return userId;
}
private void checkAutoSignIn(long userId) throws IOException {
final JsonElement response = client.execute(new HttpGet(getResourceUri("/session")), httpResponse -> {
assertHttpStatus(httpResponse, SC_OK);
return jsonResponse(httpResponse);
});
final JsonObject obj = response.getAsJsonObject();
assertTrue(obj.has("__ok"));
assertTrue(obj.get("__ok").getAsBoolean());
assertTrue(obj.has("id"));
assertEquals(obj.get("id").getAsLong(), userId);
}
private void assertHttpStatus(HttpResponse httpResponse, int statusCode) {
assertEquals(httpResponse.getStatusLine().getStatusCode(), statusCode);
}
private String getResourceUri(String resourcePart) {
return String.format(uriFormat, resourcePart);
}
private JsonElement jsonResponse(HttpResponse httpResponse) throws IOException {
return new JsonParser().parse(new InputStreamReader(httpResponse.getEntity().getContent()));
}
private static class FunctionalTestDependencyBinder extends AbstractBinder {
@Override
protected void configure() {
bind(AccountServiceMapImpl.class).to(AccountService.class).ranked(1000);
bind(SettingsServiceFixedImpl.class).to(SettingsService.class).ranked(1000);
}
}
} | Repeated Sign Up, User Profile, Profile Not Existent User test cases
| src/test/java/su/iota/backend/frontend/FunctionalTest.java | Repeated Sign Up, User Profile, Profile Not Existent User test cases | <ide><path>rc/test/java/su/iota/backend/frontend/FunctionalTest.java
<ide> import org.apache.http.client.methods.HttpPut;
<ide> import org.apache.http.entity.ByteArrayEntity;
<ide> import org.apache.http.impl.client.HttpClients;
<add>import org.eclipse.jetty.server.Authentication;
<ide> import org.eclipse.jetty.server.Server;
<ide> import org.glassfish.hk2.api.MultiException;
<ide> import org.glassfish.hk2.api.ServiceLocator;
<ide> @Test
<ide> public void testSignUpAndSignIn() throws Exception {
<ide> checkSignOut();
<del> checkIsSignedIn();
<add> checkIsNotSignedIn();
<ide>
<ide> final UserProfile userProfile = new UserProfile();
<ide> userProfile.setLogin("maxim.galaganov");
<ide> checkAutoSignIn(userId);
<ide> checkSignOut();
<ide> checkSignIn(userProfile);
<add>
<add> checkRepeatedSignUp(userProfile);
<add> checkUserProfile(userId, userProfile);
<add> checkProfileNotExistentUser(2);
<add> }
<add>
<add> private void checkProfileNotExistentUser(long userId) throws IOException {
<add> final JsonElement response = client.execute(new HttpGet(getResourceUri("/user/" + userId)), httpResponse -> {
<add> assertHttpStatus(httpResponse, SC_OK);
<add> return jsonResponse(httpResponse);
<add> });
<add> final JsonObject obj = response.getAsJsonObject();
<add> assertTrue(obj.has("__ok"));
<add> assertFalse(obj.get("__ok").getAsBoolean());
<add> }
<add>
<add> private void checkUserProfile(long userId, UserProfile userProfile) throws IOException {
<add> final JsonElement response = client.execute(new HttpGet(getResourceUri("/user/" + userId)), httpResponse -> {
<add> assertHttpStatus(httpResponse, SC_OK);
<add> return jsonResponse(httpResponse);
<add> });
<add> final JsonObject obj = response.getAsJsonObject();
<add> assertTrue(obj.has("__ok"));
<add> assertTrue(obj.get("__ok").getAsBoolean());
<add> assertTrue(obj.has("id"));
<add> assertTrue(obj.get("id").getAsLong() == userId);
<add> assertTrue(obj.has("login"));
<add> assertTrue(obj.get("login").getAsString().equals(userProfile.getLogin()));
<add> }
<add>
<add> private void checkRepeatedSignUp(UserProfile userProfile) throws IOException {
<add> final HttpPut signUpRequest = new HttpPut(getResourceUri("/user"));
<add> signUpRequest.setEntity(new ByteArrayEntity(new Gson().toJson(userProfile).getBytes()));
<add> final JsonElement response = client.execute(signUpRequest, httpResponse -> {
<add> assertHttpStatus(httpResponse, SC_OK);
<add> return jsonResponse(httpResponse);
<add> });
<add> final JsonObject obj = response.getAsJsonObject();
<add> assertTrue(obj.has("__ok"));
<add> assertFalse(obj.get("__ok").getAsBoolean());
<ide> }
<ide>
<ide> private void checkSignIn(UserProfile userProfile) throws IOException {
<ide> assertTrue(obj.get("__ok").getAsBoolean());
<ide> }
<ide>
<del> private void checkIsSignedIn() throws IOException {
<add> private void checkIsNotSignedIn() throws IOException {
<ide> final JsonElement response = client.execute(new HttpGet(getResourceUri("/session")), httpResponse -> {
<ide> assertHttpStatus(httpResponse, SC_OK);
<ide> return jsonResponse(httpResponse); |
|
Java | apache-2.0 | 45653690a32a6ca1aff8006a89ccabc66d9093ed | 0 | jmptrader/Strata,OpenGamma/Strata,nssales/Strata,ChinaQuants/Strata | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.platform.finance.swap;
import org.joda.convert.FromString;
import org.joda.convert.ToString;
import com.google.common.base.CaseFormat;
import com.opengamma.collect.ArgChecker;
/**
* A convention defining how to compound interest.
* <p>
* When calculating interest, it may be necessary to apply compounding.
* Compound interest occurs where the basic interest is collected over one period but paid over a longer period.
* For example, interest may be collected every three months but only paid every year.
* <p>
* For more information see this <a href="http://www.isda.org/c_and_a/pdf/ISDA-Compounding-memo.pdf">ISDA note</a>.
*/
public enum CompoundingMethod {
/**
* No compounding applies.
* <p>
* This is typically used when the payment periods align with the accrual periods
* thus no compounding is necessary. It may also be used when there are multiple
* accrual periods, but they are summed rather than compounded.
*/
NONE,
/**
* Straight compounding applies, which is inclusive of the spread.
* <p>
* Compounding is based on the total of the observed rate and the spread.
* <p>
* Defined as "Compounding" in the ISDA 2006 definitions.
*/
STRAIGHT,
/**
* Flat compounding applies.
* <p>
* Compounding is based for each period on the total of the observed rate and the spread
* for the interest on the notional, known as the <i>Basic Compounding Period Amount</i>,
* but only the observed rate (and not the spread) for the interest on previous periods
* interest, known as the <i>Additional Compounding Period Amount</i>.
* <p>
* Defined as "Flat Compounding" in the ISDA 2006 definitions.
*/
FLAT,
/**
* Spread exclusive compounding applies.
* <p>
* Compounding is based only on the observed rate, with the spread treated as simple interest.
* <p>
* Defined as "Compounding treating Spread as simple interest" in the ISDA definitions.
*/
SPREAD_EXCLUSIVE;
//-------------------------------------------------------------------------
/**
* Obtains the compounding method from a unique name.
*
* @param uniqueName the unique name
* @return the compounding method
* @throws IllegalArgumentException if the name is not known
*/
@FromString
public static CompoundingMethod of(String uniqueName) {
ArgChecker.notNull(uniqueName, "uniqueName");
return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName));
}
/**
* Returns the formatted unique name of the compounding method.
*
* @return the formatted string representing the compounding method
*/
@ToString
@Override
public String toString() {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());
}
}
| modules/finance/src/main/java/com/opengamma/platform/finance/swap/CompoundingMethod.java | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.platform.finance.swap;
import org.joda.convert.FromString;
import org.joda.convert.ToString;
import com.google.common.base.CaseFormat;
import com.opengamma.collect.ArgChecker;
/**
* A convention defining how to compound interest.
* <p>
* When calculating interest, it may be necessary to apply compounding.
* Compound interest occurs where the basic interest is collected over one period but paid over a longer period.
* For example, interest may be collected every three months but only paid every year.
* <p>
* For more information see this <a href="http://www.isda.org/c_and_a/pdf/ISDA-Compounding-memo.pdf">ISDA note</a>.
*/
public enum CompoundingMethod {
/**
* No compounding applies.
* <p>
* This is typically used when the payment periods align with the accrual periods
* thus no compounding is necessary. It may also be used when there are multiple
* accrual periods, but they are summed rather than compounded.
*/
NONE,
/**
* Straight compounding applies, which is inclusive of the spread.
* <p>
* Compounding is based on the total of the observed rate and the spread.
* <p>
* Defined as "Compounding" in the ISDA 2006 definitions.
*/
STRAIGHT,
/**
* Flat compounding applies.
* <p>
* Compounding is based on the total of the observed rate and the spread in the
* first period, but only the observed rate in subsequent periods.
* <p>
* Defined as "Flat Compounding" in the ISDA 2006 definitions.
*/
FLAT,
/**
* Spread exclusive compounding applies.
* <p>
* Compounding is based only on the observed rate, with the spread treated as simple interest.
* <p>
* Defined as "Compounding treating Spread as simple interest" in the ISDA definitions.
*/
SPREAD_EXCLUSIVE;
//-------------------------------------------------------------------------
/**
* Obtains the compounding method from a unique name.
*
* @param uniqueName the unique name
* @return the compounding method
* @throws IllegalArgumentException if the name is not known
*/
@FromString
public static CompoundingMethod of(String uniqueName) {
ArgChecker.notNull(uniqueName, "uniqueName");
return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName));
}
/**
* Returns the formatted unique name of the compounding method.
*
* @return the formatted string representing the compounding method
*/
@ToString
@Override
public String toString() {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());
}
}
| PLT-533 Swap domain model
Fixup definition of compounding
| modules/finance/src/main/java/com/opengamma/platform/finance/swap/CompoundingMethod.java | PLT-533 Swap domain model | <ide><path>odules/finance/src/main/java/com/opengamma/platform/finance/swap/CompoundingMethod.java
<ide> /**
<ide> * Flat compounding applies.
<ide> * <p>
<del> * Compounding is based on the total of the observed rate and the spread in the
<del> * first period, but only the observed rate in subsequent periods.
<add> * Compounding is based for each period on the total of the observed rate and the spread
<add> * for the interest on the notional, known as the <i>Basic Compounding Period Amount</i>,
<add> * but only the observed rate (and not the spread) for the interest on previous periods
<add> * interest, known as the <i>Additional Compounding Period Amount</i>.
<ide> * <p>
<ide> * Defined as "Flat Compounding" in the ISDA 2006 definitions.
<ide> */ |
|
Java | lgpl-2.1 | b0ca4d37797304509914577f55478461062a8643 | 0 | liujed/polyglot-eclipse,liujed/polyglot-eclipse,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,xcv58/polyglot,xcv58/polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot | package polyglot.ext.jl.ast;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.util.*;
import polyglot.visit.*;
import polyglot.frontend.*;
import polyglot.main.Report;
import java.util.*;
/**
* A <code>ClassDecl</code> is the definition of a class, abstract class,
* or interface. It may be a public or other top-level class, or an inner
* named class, or an anonymous class.
*/
public class ClassDecl_c extends Node_c implements ClassDecl
{
protected Flags flags;
protected String name;
protected TypeNode superClass;
protected List interfaces;
protected ClassBody body;
protected ParsedClassType type;
public ClassDecl_c(Position pos, Flags flags, String name, TypeNode superClass, List interfaces, ClassBody body) {
super(pos);
this.flags = flags;
this.name = name;
this.superClass = superClass;
this.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
this.body = body;
}
public ParsedClassType type() {
return type;
}
public ClassDecl type(ParsedClassType type) {
ClassDecl_c n = (ClassDecl_c) copy();
n.type = type;
return n;
}
public Flags flags() {
return this.flags;
}
public ClassDecl flags(Flags flags) {
ClassDecl_c n = (ClassDecl_c) copy();
n.flags = flags;
return n;
}
public String name() {
return this.name;
}
public ClassDecl name(String name) {
ClassDecl_c n = (ClassDecl_c) copy();
n.name = name;
return n;
}
public TypeNode superClass() {
return this.superClass;
}
public ClassDecl superClass(TypeNode superClass) {
ClassDecl_c n = (ClassDecl_c) copy();
n.superClass = superClass;
return n;
}
public List interfaces() {
return this.interfaces;
}
public ClassDecl interfaces(List interfaces) {
ClassDecl_c n = (ClassDecl_c) copy();
n.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
return n;
}
public ClassBody body() {
return this.body;
}
public ClassDecl body(ClassBody body) {
ClassDecl_c n = (ClassDecl_c) copy();
n.body = body;
return n;
}
protected ClassDecl_c reconstruct(TypeNode superClass, List interfaces, ClassBody body) {
if (superClass != this.superClass || ! CollectionUtil.equals(interfaces, this.interfaces) || body != this.body) {
ClassDecl_c n = (ClassDecl_c) copy();
n.superClass = superClass;
n.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
n.body = body;
return n;
}
return this;
}
public Node visitChildren(NodeVisitor v) {
TypeNode superClass = (TypeNode) visitChild(this.superClass, v);
List interfaces = visitList(this.interfaces, v);
ClassBody body = (ClassBody) visitChild(this.body, v);
return reconstruct(superClass, interfaces, body);
}
public NodeVisitor buildTypesEnter(TypeBuilder tb) throws SemanticException {
TypeSystem ts = tb.typeSystem();
tb = tb.pushClass(position(), flags, name);
// Member classes of interfaces are implicitly static.
ParsedClassType ct = tb.currentClass();
if (ct.isMember() && ct.outer().flags().isInterface()) {
ct.flags(ct.flags().Static());
}
// Member interfaces are implicitly static.
if (ct.isMember() && ct.flags().isInterface()) {
ct.flags(ct.flags().Static());
}
// Interfaces are implicitly abstract.
if (ct.flags().isInterface()) {
ct.flags(ct.flags().Abstract());
}
return tb;
}
public Node buildTypes(TypeBuilder tb) throws SemanticException {
ParsedClassType type = tb.currentClass();
return type(type).flags(type.flags());
}
public Context enterScope(Context c) {
TypeSystem ts = c.typeSystem();
return c.pushClass(type, ts.staticTarget(type).toClass());
}
public NodeVisitor disambiguateEnter(AmbiguityRemover ar) throws SemanticException {
if (ar.kind() == AmbiguityRemover.SUPER) {
return ar.bypass(body);
}
return ar;
}
protected void disambiguateSuperType(AmbiguityRemover ar) throws SemanticException {
TypeSystem ts = ar.typeSystem();
if (this.superClass != null) {
Type t = this.superClass.type();
if (! t.isCanonical()) {
throw new SemanticException("Could not disambiguate super" +
" class of " + type + ".", superClass.position());
}
if (! t.isClass() || t.toClass().flags().isInterface()) {
throw new SemanticException("Super class " + t + " of " +
type + " is not a class.", superClass.position());
}
if (Report.should_report(Report.types, 3))
Report.report(3, "setting super type of " + this.type + " to " + t);
this.type.superType(t);
ts.checkCycles(t.toReference());
}
else if (ts.Object() != this.type &&
!ts.Object().fullName().equals(this.type.fullName())) {
// the supertype was not specified, and the type is not the same
// as ts.Object() (which is typically java.lang.Object)
// As such, the default supertype is ts.Object().
this.type.superType(ts.Object());
}
else {
// the type is the same as ts.Object(), so it has no supertype.
this.type.superType(null);
}
}
public Node disambiguate(AmbiguityRemover ar) throws SemanticException {
if (ar.kind() != AmbiguityRemover.SUPER) {
return this;
}
TypeSystem ts = ar.typeSystem();
if (Report.should_report(Report.types, 2))
Report.report(2, "Cleaning " + type + ".");
disambiguateSuperType(ar);
for (Iterator i = this.interfaces.iterator(); i.hasNext(); ) {
TypeNode tn = (TypeNode) i.next();
Type t = tn.type();
if (! t.isCanonical()) {
throw new SemanticException("Could not disambiguate super" +
" class of " + type + ".", tn.position());
}
if (! t.isClass() || ! t.toClass().flags().isInterface()) {
throw new SemanticException("Interface " + t + " of " +
type + " is not an interface.", tn.position());
}
if (Report.should_report(Report.types, 3))
Report.report(3, "adding interface of " + this.type + " to " + t);
this.type.addInterface(t);
ts.checkCycles(t.toReference());
}
return this;
}
public Node addMembers(AddMemberVisitor tc) throws SemanticException {
TypeSystem ts = tc.typeSystem();
NodeFactory nf = tc.nodeFactory();
return addDefaultConstructorIfNeeded(ts, nf);
}
protected Node addDefaultConstructorIfNeeded(TypeSystem ts,
NodeFactory nf) {
if (defaultConstructorNeeded()) {
return addDefaultConstructor(ts, nf);
}
return this;
}
protected boolean defaultConstructorNeeded() {
if (flags().isInterface()) {
return false;
}
return type().constructors().isEmpty();
}
protected Node addDefaultConstructor(TypeSystem ts, NodeFactory nf) {
ConstructorInstance ci = ts.defaultConstructor(position(), this.type);
this.type.addConstructor(ci);
ConstructorDecl cd = nf.ConstructorDecl(position(), Flags.PUBLIC,
name, Collections.EMPTY_LIST,
Collections.EMPTY_LIST,
nf.Block(position(),
nf.SuperCall(position(),
Collections.EMPTY_LIST)));
cd = (ConstructorDecl) cd.constructorInstance(ci);
return body(body.addMember(cd));
}
public Node typeCheck(TypeChecker tc) throws SemanticException {
// The class cannot have the same simple name as any enclosing class.
if (this.type.isMember()) {
ClassType container = this.type.outer();
while (container instanceof Named) {
String name = ((Named) container).name();
if (name.equals(this.name)) {
throw new SemanticException("Cannot declare member " +
"class \"" + this.type +
"\" inside class with the " +
"same name.", position());
}
if (container.isMember()) {
container = container.outer();
}
else {
break;
}
}
}
// Make sure that static members are not declared inside inner classes
// (recall that, according to the JLS, static member classes are not
// really inner classes since they may not refer to their outer
// instance).
if (this.type.isMember() && this.type.flags().isStatic()) {
ClassType container = this.type.outer();
if (container.isMember() && ! container.flags().isStatic() ||
container.isLocal() || container.isAnonymous()) {
throw new SemanticException("Cannot declare static member " +
"class \"" + this.type +
"\" inside inner class \"" +
container + "\".", position());
}
}
if (type.superType() != null) {
if (! type.superType().isClass()) {
throw new SemanticException("Cannot extend non-class \"" +
type.superType() + "\".",
position());
}
if (type.superType().toClass().flags().isFinal()) {
throw new SemanticException("Cannot extend final class \"" +
type.superType() + "\".",
position());
}
}
TypeSystem ts = tc.typeSystem();
try {
if (type.isTopLevel()) {
ts.checkTopLevelClassFlags(type.flags());
}
if (type.isMember()) {
ts.checkMemberClassFlags(type.flags());
}
if (type.isLocal()) {
ts.checkLocalClassFlags(type.flags());
}
}
catch (SemanticException e) {
throw new SemanticException(e.getMessage(), position());
}
// check the class implements all abstract methods that it needs to.
ts.checkClassConformance(type);
return this;
}
public String toString() {
return flags.clearInterface().translate() +
(flags.isInterface() ? "interface " : "class ") + name + " " + body;
}
public void prettyPrintHeader(CodeWriter w, PrettyPrinter tr) {
if (flags.isInterface()) {
w.write(flags.clearInterface().clearAbstract().translate());
}
else {
w.write(flags.translate());
}
if (flags.isInterface()) {
w.write("interface ");
}
else {
w.write("class ");
}
w.write(name);
if (superClass() != null) {
w.write(" extends ");
print(superClass(), w, tr);
}
if (! interfaces.isEmpty()) {
if (flags.isInterface()) {
w.write(" extends ");
}
else {
w.write(" implements ");
}
for (Iterator i = interfaces().iterator(); i.hasNext(); ) {
TypeNode tn = (TypeNode) i.next();
print(tn, w, tr);
if (i.hasNext()) {
w.write (", ");
}
}
}
w.write(" {");
}
public void prettyPrintFooter(CodeWriter w, PrettyPrinter tr) {
w.write("}");
w.newline(0);
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
prettyPrintHeader(w, tr);
print(body(), w, tr);
prettyPrintFooter(w, tr);
}
public void dump(CodeWriter w) {
super.dump(w);
w.allowBreak(4, " ");
w.begin(0);
w.write("(name " + name + ")");
w.end();
if (type != null) {
w.allowBreak(4, " ");
w.begin(0);
w.write("(type " + type + ")");
w.end();
}
}
}
| src/polyglot/ast/ClassDecl_c.java | package polyglot.ext.jl.ast;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.util.*;
import polyglot.visit.*;
import polyglot.frontend.*;
import polyglot.main.Report;
import java.util.*;
/**
* A <code>ClassDecl</code> is the definition of a class, abstract class,
* or interface. It may be a public or other top-level class, or an inner
* named class, or an anonymous class.
*/
public class ClassDecl_c extends Node_c implements ClassDecl
{
protected Flags flags;
protected String name;
protected TypeNode superClass;
protected List interfaces;
protected ClassBody body;
protected ParsedClassType type;
public ClassDecl_c(Position pos, Flags flags, String name, TypeNode superClass, List interfaces, ClassBody body) {
super(pos);
this.flags = flags;
this.name = name;
this.superClass = superClass;
this.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
this.body = body;
}
public ParsedClassType type() {
return type;
}
public ClassDecl type(ParsedClassType type) {
ClassDecl_c n = (ClassDecl_c) copy();
n.type = type;
return n;
}
public Flags flags() {
return this.flags;
}
public ClassDecl flags(Flags flags) {
ClassDecl_c n = (ClassDecl_c) copy();
n.flags = flags;
return n;
}
public String name() {
return this.name;
}
public ClassDecl name(String name) {
ClassDecl_c n = (ClassDecl_c) copy();
n.name = name;
return n;
}
public TypeNode superClass() {
return this.superClass;
}
public ClassDecl superClass(TypeNode superClass) {
ClassDecl_c n = (ClassDecl_c) copy();
n.superClass = superClass;
return n;
}
public List interfaces() {
return this.interfaces;
}
public ClassDecl interfaces(List interfaces) {
ClassDecl_c n = (ClassDecl_c) copy();
n.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
return n;
}
public ClassBody body() {
return this.body;
}
public ClassDecl body(ClassBody body) {
ClassDecl_c n = (ClassDecl_c) copy();
n.body = body;
return n;
}
protected ClassDecl_c reconstruct(TypeNode superClass, List interfaces, ClassBody body) {
if (superClass != this.superClass || ! CollectionUtil.equals(interfaces, this.interfaces) || body != this.body) {
ClassDecl_c n = (ClassDecl_c) copy();
n.superClass = superClass;
n.interfaces = TypedList.copyAndCheck(interfaces, TypeNode.class, true);
n.body = body;
return n;
}
return this;
}
public Node visitChildren(NodeVisitor v) {
TypeNode superClass = (TypeNode) visitChild(this.superClass, v);
List interfaces = visitList(this.interfaces, v);
ClassBody body = (ClassBody) visitChild(this.body, v);
return reconstruct(superClass, interfaces, body);
}
public NodeVisitor buildTypesEnter(TypeBuilder tb) throws SemanticException {
TypeSystem ts = tb.typeSystem();
tb = tb.pushClass(position(), flags, name);
// Member classes of interfaces are implicitly static.
ParsedClassType ct = tb.currentClass();
if (ct.isMember() && ct.outer().flags().isInterface()) {
ct.flags(ct.flags().Static());
}
// Member interfaces are implicitly static.
if (ct.isMember() && ct.flags().isInterface()) {
ct.flags(ct.flags().Static());
}
// Interfaces are implicitly abstract.
if (ct.flags().isInterface()) {
ct.flags(ct.flags().Abstract());
}
return tb;
}
public Node buildTypes(TypeBuilder tb) throws SemanticException {
ParsedClassType type = tb.currentClass();
return type(type).flags(type.flags());
}
public Context enterScope(Context c) {
TypeSystem ts = c.typeSystem();
return c.pushClass(type, ts.staticTarget(type).toClass());
}
public NodeVisitor disambiguateEnter(AmbiguityRemover ar) throws SemanticException {
if (ar.kind() == AmbiguityRemover.SUPER) {
return ar.bypass(body);
}
return ar;
}
public Node disambiguate(AmbiguityRemover ar) throws SemanticException {
if (ar.kind() != AmbiguityRemover.SUPER) {
return this;
}
TypeSystem ts = ar.typeSystem();
if (Report.should_report(Report.types, 2))
Report.report(2, "Cleaning " + type + ".");
if (this.superClass != null) {
Type t = this.superClass.type();
if (! t.isCanonical()) {
throw new SemanticException("Could not disambiguate super" +
" class of " + type + ".", superClass.position());
}
if (! t.isClass() || t.toClass().flags().isInterface()) {
throw new SemanticException("Super class " + t + " of " +
type + " is not a class.", superClass.position());
}
if (Report.should_report(Report.types, 3))
Report.report(3, "setting super type of " + this.type + " to " + t);
this.type.superType(t);
ts.checkCycles(t.toReference());
}
else if (this.type != ts.Object()) {
this.type.superType(ts.Object());
}
else {
this.type.superType(null);
}
for (Iterator i = this.interfaces.iterator(); i.hasNext(); ) {
TypeNode tn = (TypeNode) i.next();
Type t = tn.type();
if (! t.isCanonical()) {
throw new SemanticException("Could not disambiguate super" +
" class of " + type + ".", tn.position());
}
if (! t.isClass() || ! t.toClass().flags().isInterface()) {
throw new SemanticException("Interface " + t + " of " +
type + " is not an interface.", tn.position());
}
if (Report.should_report(Report.types, 3))
Report.report(3, "adding interface of " + this.type + " to " + t);
this.type.addInterface(t);
ts.checkCycles(t.toReference());
}
return this;
}
public Node addMembers(AddMemberVisitor tc) throws SemanticException {
TypeSystem ts = tc.typeSystem();
NodeFactory nf = tc.nodeFactory();
return addDefaultConstructorIfNeeded(ts, nf);
}
protected Node addDefaultConstructorIfNeeded(TypeSystem ts,
NodeFactory nf) {
if (defaultConstructorNeeded()) {
return addDefaultConstructor(ts, nf);
}
return this;
}
protected boolean defaultConstructorNeeded() {
if (flags().isInterface()) {
return false;
}
return type().constructors().isEmpty();
}
protected Node addDefaultConstructor(TypeSystem ts, NodeFactory nf) {
ConstructorInstance ci = ts.defaultConstructor(position(), this.type);
this.type.addConstructor(ci);
ConstructorDecl cd = nf.ConstructorDecl(position(), Flags.PUBLIC,
name, Collections.EMPTY_LIST,
Collections.EMPTY_LIST,
nf.Block(position(),
nf.SuperCall(position(),
Collections.EMPTY_LIST)));
cd = (ConstructorDecl) cd.constructorInstance(ci);
return body(body.addMember(cd));
}
public Node typeCheck(TypeChecker tc) throws SemanticException {
// The class cannot have the same simple name as any enclosing class.
if (this.type.isMember()) {
ClassType container = this.type.outer();
while (container instanceof Named) {
String name = ((Named) container).name();
if (name.equals(this.name)) {
throw new SemanticException("Cannot declare member " +
"class \"" + this.type +
"\" inside class with the " +
"same name.", position());
}
if (container.isMember()) {
container = container.outer();
}
else {
break;
}
}
}
// Make sure that static members are not declared inside inner classes
// (recall that, according to the JLS, static member classes are not
// really inner classes since they may not refer to their outer
// instance).
if (this.type.isMember() && this.type.flags().isStatic()) {
ClassType container = this.type.outer();
if (container.isMember() && ! container.flags().isStatic() ||
container.isLocal() || container.isAnonymous()) {
throw new SemanticException("Cannot declare static member " +
"class \"" + this.type +
"\" inside inner class \"" +
container + "\".", position());
}
}
if (type.superType() != null) {
if (! type.superType().isClass()) {
throw new SemanticException("Cannot extend non-class \"" +
type.superType() + "\".",
position());
}
if (type.superType().toClass().flags().isFinal()) {
throw new SemanticException("Cannot extend final class \"" +
type.superType() + "\".",
position());
}
}
TypeSystem ts = tc.typeSystem();
try {
if (type.isTopLevel()) {
ts.checkTopLevelClassFlags(type.flags());
}
if (type.isMember()) {
ts.checkMemberClassFlags(type.flags());
}
if (type.isLocal()) {
ts.checkLocalClassFlags(type.flags());
}
}
catch (SemanticException e) {
throw new SemanticException(e.getMessage(), position());
}
// check the class implements all abstract methods that it needs to.
ts.checkClassConformance(type);
return this;
}
public String toString() {
return flags.clearInterface().translate() +
(flags.isInterface() ? "interface " : "class ") + name + " " + body;
}
public void prettyPrintHeader(CodeWriter w, PrettyPrinter tr) {
if (flags.isInterface()) {
w.write(flags.clearInterface().clearAbstract().translate());
}
else {
w.write(flags.translate());
}
if (flags.isInterface()) {
w.write("interface ");
}
else {
w.write("class ");
}
w.write(name);
if (superClass() != null) {
w.write(" extends ");
print(superClass(), w, tr);
}
if (! interfaces.isEmpty()) {
if (flags.isInterface()) {
w.write(" extends ");
}
else {
w.write(" implements ");
}
for (Iterator i = interfaces().iterator(); i.hasNext(); ) {
TypeNode tn = (TypeNode) i.next();
print(tn, w, tr);
if (i.hasNext()) {
w.write (", ");
}
}
}
w.write(" {");
}
public void prettyPrintFooter(CodeWriter w, PrettyPrinter tr) {
w.write("}");
w.newline(0);
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
prettyPrintHeader(w, tr);
print(body(), w, tr);
prettyPrintFooter(w, tr);
}
public void dump(CodeWriter w) {
super.dump(w);
w.allowBreak(4, " ");
w.begin(0);
w.write("(name " + name + ")");
w.end();
if (type != null) {
w.allowBreak(4, " ");
w.begin(0);
w.write("(type " + type + ")");
w.end();
}
}
}
| Modified the disambiguation of the supertype, so that if we are compiling the Object class (generally java.lang.Object) we do not automatically set the supertype to TypeSystem.Object(), but instead set it to null. This allows extensions to write source code for java.lang.Object, and compile it correctly.
| src/polyglot/ast/ClassDecl_c.java | Modified the disambiguation of the supertype, so that if we are compiling the Object class (generally java.lang.Object) we do not automatically set the supertype to TypeSystem.Object(), but instead set it to null. This allows extensions to write source code for java.lang.Object, and compile it correctly. | <ide><path>rc/polyglot/ast/ClassDecl_c.java
<ide> return ar;
<ide> }
<ide>
<add> protected void disambiguateSuperType(AmbiguityRemover ar) throws SemanticException {
<add> TypeSystem ts = ar.typeSystem();
<add>
<add> if (this.superClass != null) {
<add> Type t = this.superClass.type();
<add>
<add> if (! t.isCanonical()) {
<add> throw new SemanticException("Could not disambiguate super" +
<add> " class of " + type + ".", superClass.position());
<add> }
<add>
<add> if (! t.isClass() || t.toClass().flags().isInterface()) {
<add> throw new SemanticException("Super class " + t + " of " +
<add> type + " is not a class.", superClass.position());
<add> }
<add>
<add> if (Report.should_report(Report.types, 3))
<add> Report.report(3, "setting super type of " + this.type + " to " + t);
<add>
<add> this.type.superType(t);
<add>
<add> ts.checkCycles(t.toReference());
<add> }
<add> else if (ts.Object() != this.type &&
<add> !ts.Object().fullName().equals(this.type.fullName())) {
<add> // the supertype was not specified, and the type is not the same
<add> // as ts.Object() (which is typically java.lang.Object)
<add> // As such, the default supertype is ts.Object().
<add> this.type.superType(ts.Object());
<add> }
<add> else {
<add> // the type is the same as ts.Object(), so it has no supertype.
<add> this.type.superType(null);
<add> }
<add> }
<add>
<ide> public Node disambiguate(AmbiguityRemover ar) throws SemanticException {
<ide> if (ar.kind() != AmbiguityRemover.SUPER) {
<ide> return this;
<ide> if (Report.should_report(Report.types, 2))
<ide> Report.report(2, "Cleaning " + type + ".");
<ide>
<del> if (this.superClass != null) {
<del> Type t = this.superClass.type();
<del>
<del> if (! t.isCanonical()) {
<del> throw new SemanticException("Could not disambiguate super" +
<del> " class of " + type + ".", superClass.position());
<del> }
<del>
<del> if (! t.isClass() || t.toClass().flags().isInterface()) {
<del> throw new SemanticException("Super class " + t + " of " +
<del> type + " is not a class.", superClass.position());
<del> }
<del>
<del> if (Report.should_report(Report.types, 3))
<del> Report.report(3, "setting super type of " + this.type + " to " + t);
<del>
<del> this.type.superType(t);
<del>
<del> ts.checkCycles(t.toReference());
<del> }
<del> else if (this.type != ts.Object()) {
<del> this.type.superType(ts.Object());
<del> }
<del> else {
<del> this.type.superType(null);
<del> }
<del>
<add> disambiguateSuperType(ar);
<add>
<ide> for (Iterator i = this.interfaces.iterator(); i.hasNext(); ) {
<ide> TypeNode tn = (TypeNode) i.next();
<ide> Type t = tn.type(); |
|
Java | mit | fc98528b554789827a1c099aa8b3557ef89b52f3 | 0 | jtechapps/FloppyThreeD,jtechapps/FloppyThreeD,jtechapps/FloppyThreeD | package com.jtechapps.FloppyThreeD.Screens;
import java.util.Iterator;
import java.util.Random;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper;
import com.badlogic.gdx.physics.bullet.collision.btBoxShape;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithmConstructionInfo;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.collision.btCylinderShape;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo;
import com.badlogic.gdx.physics.bullet.collision.btManifoldResult;
import com.badlogic.gdx.physics.bullet.collision.btSphereBoxCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btSphereShape;
import com.badlogic.gdx.utils.Array;
public class ClassicGameScreen implements Screen, InputProcessor {
public PerspectiveCamera camera;
private float width;
private float height;
public ModelBatch modelBatch;
public Model model;//create 500*5*500 floor
public Array<ModelInstance> instances;
public Array<ModelInstance> pipeinstances;
public Array<ModelInstance> toppipeinstances;
public Environment environment;
public CameraInputController camController;
ModelInstance playerinstance;
private int blockscale = 5;//pipe height max 65 or 75
private float pipespeed = 0.5f;
private Texture groundTexture;
private float gravity = -65.0f;
private float playerforce = 0.0f;
boolean collision;
private boolean touched;
private boolean dead;
//physics
btCollisionShape groundShape;
btCollisionShape ballShape;
btCollisionShape pipeShape;
btCollisionObject groundObject;
btCollisionObject ballObject;
btCollisionConfiguration collisionConfig;
btDispatcher dispatcher;
private Array<btCollisionObject> pipecollisions;
private Array<btCollisionObject> toppipecollisions;
Game g;
private Sound dieSound;
private Sound flopSound;
private Sound scoreSound;
private int score = 0;
public ClassicGameScreen(Game game){
g = game;
}
@Override
public void render(float delta) {
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(camera);
for (ModelInstance minstance : instances) {
modelBatch.render(minstance, environment);
}
for (int arrayint = 0; arrayint < pipeinstances.size; arrayint++){
if(touched && !dead){
pipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
pipecollisions.get(arrayint).setWorldTransform(pipeinstances.get(arrayint).transform);
collision = checkCollision(pipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(pipeinstances.get(arrayint), environment);
}
for (int arrayint = 0; arrayint < toppipeinstances.size; arrayint++) {
if(touched && !dead){
toppipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
toppipecollisions.get(arrayint).setWorldTransform(toppipeinstances.get(arrayint).transform);
collision = checkCollision(toppipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(toppipeinstances.get(arrayint), environment);
}
//check if pipes moved off screen.
Iterator<ModelInstance> iter = pipeinstances.iterator();
while(iter.hasNext()) {
ModelInstance pipe = iter.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
Vector3 playertmp = new Vector3();
playerinstance.transform.getTranslation(playertmp);
float playerx = playertmp.x;
if(x == 50*blockscale){//middle
spawnpipes(pipeinstances, toppipeinstances);
}
if(x == playerx){//add score
addscore();
}
if(x >= 60*blockscale){//left side
iter.remove();
}
}
Iterator<ModelInstance> iter2 = toppipeinstances.iterator();
while(iter2.hasNext()) {
ModelInstance pipe = iter2.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter2.remove();
}
}
Iterator<btCollisionObject> iter3 = pipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter3.hasNext()) {
btCollisionObject pipe = iter3.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter3.remove();
}
}
Iterator<btCollisionObject> iter4 = toppipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter4.hasNext()) {
btCollisionObject pipe = iter4.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter4.remove();
}
}
//player physics
if(!collision && touched && !dead){
//gravity
playerinstance.transform.translate(0, gravity*delta, 0);
//jumps
float playerforcetoapply = playerforce*delta*2;
playerforce-=playerforcetoapply;
if(playerforce<=0){
playerforce = 0.0f;
}
playerinstance.transform.translate(0, playerforcetoapply/2, 0);
ballObject.setWorldTransform(playerinstance.transform);
collision = checkCollision();
if(collision){
playerdie();
}
Vector3 playertmppos = new Vector3();
playerinstance.transform.getTranslation(playertmppos);
if(playertmppos.y >= 90){
playerdie();
}
}
else if(touched && dead && collision){
playerinstance.transform.translate(0, gravity*delta, 0);
}
modelBatch.render(playerinstance, environment);
modelBatch.end();
}
private void addscore(){
score++;
scoreSound.play();
Gdx.app.log("score ", ""+score);
}
private void playerdie(){
//play sound and wait
dieSound.play();
dead = true;
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
Bullet.init();
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
camera = new PerspectiveCamera(67, 640*2, 480*2);
camera.position.set(50.0f*blockscale, 25.0f, 0.0f);
camera.lookAt(50.0f*blockscale, 25.0f, 50.0f*blockscale);
camera.near = 1f;
camera.far = 300f;
camera.update();
modelBatch = new ModelBatch();
instances = new Array<ModelInstance>();
pipeinstances = new Array<ModelInstance>();
toppipeinstances = new Array<ModelInstance>();
pipecollisions = new Array<btCollisionObject>();
toppipecollisions = new Array<btCollisionObject>();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f,
0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f,
-0.8f, -0.2f));
//environment.set(new ColorAttribute(ColorAttribute.Fog, 1f, 0.1f, 0.1f, 1.0f));
//physics
ballShape = new btSphereShape(4.0f);
pipeShape = new btCylinderShape(new Vector3(5.0f, 75.0f/2, 5.0f));
groundShape = new btBoxShape(new Vector3(50.0f*blockscale, 0.5f*blockscale, 50.0f*blockscale));
collisionConfig = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfig);
spawnfloor();
spawnpipes(pipeinstances, toppipeinstances);
spawnplayer();
groundObject = new btCollisionObject();
groundObject.setCollisionShape(groundShape);
groundObject.setWorldTransform(instances.peek().transform);
ballObject = new btCollisionObject();
ballObject.setCollisionShape(ballShape);
ballObject.setWorldTransform(playerinstance.transform);
//sounds
flopSound = Gdx.audio.newSound(Gdx.files.internal("sounds/switch.wav"));
dieSound = Gdx.audio.newSound(Gdx.files.internal("sounds/die.wav"));
scoreSound = Gdx.audio.newSound(Gdx.files.internal("sounds/point.wav"));
Gdx.input.setInputProcessor(this);
}
public void spawnfloor(){
groundTexture = new Texture("img/grass.png");
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
/*model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
TextureAttribute.createDiffuse(groundTexture)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);*/
model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
ColorAttribute.createDiffuse(Color.CLEAR)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(blockscale*50, -20.0f, blockscale*50);
instances.add(instance);
}
public void spawnCubeArray(Array<ModelInstance> cubeinstances){
for (int z = 0; z < 100; z++) {
for (int x = 0; x < 100; x++) {
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
if (x % 2 == 0) {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
else {
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
} else {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
else{
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
}
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(x * blockscale, 0, z*blockscale);
cubeinstances.add(instance);
}
}
}
public void spawnplayer(){
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(8.0f, 8.0f, 8.0f, 100, 100, new Material(ColorAttribute.createDiffuse(Color.MAROON)), Usage.Position | Usage.Normal);
playerinstance = new ModelInstance(model);
playerinstance.transform.translate(53.0f*blockscale, 40.0f, 10.0f*blockscale);
}
public void spawnpipes(Array<ModelInstance> pinstances, Array<ModelInstance> tinstances){
Random rn = new Random();
int random = rn.nextInt(29) + 1;
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
model = modelBuilder.createCylinder(10.0f, 75.0f, 10.0f, 100, new Material(
ColorAttribute.createDiffuse(Color.MAGENTA)), Usage.Position | Usage.Normal);
ModelInstance bottompipeinstance = new ModelInstance(model);
ModelInstance toppipeinstance = new ModelInstance(model);
bottompipeinstance.transform.translate(40.0f*blockscale, -5.0f-random, 10.0f*blockscale);
toppipeinstance.transform.translate(40.0f*blockscale, 95.0f-random, 10.0f*blockscale);
pinstances.add(bottompipeinstance);
tinstances.add(toppipeinstance);
btCollisionObject bottompipeObject = new btCollisionObject();
bottompipeObject.setCollisionShape(pipeShape);
bottompipeObject.setWorldTransform(bottompipeinstance.transform);
btCollisionObject toppipeObject = new btCollisionObject();
toppipeObject.setCollisionShape(pipeShape);
toppipeObject.setWorldTransform(toppipeinstance.transform);
pipecollisions.add(bottompipeObject);
toppipecollisions.add(toppipeObject);
}
private void jump(){
if(!touched)
touched=true;
if(!dead){
playerforce+=100.0f;
flopSound.play();
}
else {
g.setScreen(new ClassicGameScreen(g));
}
}
boolean checkCollision() {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(groundObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
boolean checkCollision(btCollisionObject colObject) {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(colObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
@Override
public void hide() {
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
model.dispose();
modelBatch.dispose();
groundTexture.dispose();
groundObject.dispose();
groundShape.dispose();
ballObject.dispose();
ballShape.dispose();
pipeShape.dispose();
dispatcher.dispose();
collisionConfig.dispose();
dieSound.dispose();
flopSound.dispose();
scoreSound.dispose();
this.dispose();
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.SPACE){
jump();
}
return false;
}
@Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
jump();
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
| core/src/com/jtechapps/FloppyThreeD/Screens/ClassicGameScreen.java | package com.jtechapps.FloppyThreeD.Screens;
import java.util.Iterator;
import java.util.Random;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper;
import com.badlogic.gdx.physics.bullet.collision.btBoxShape;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithmConstructionInfo;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.collision.btCylinderShape;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo;
import com.badlogic.gdx.physics.bullet.collision.btManifoldResult;
import com.badlogic.gdx.physics.bullet.collision.btSphereBoxCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btSphereShape;
import com.badlogic.gdx.utils.Array;
public class ClassicGameScreen implements Screen, InputProcessor {
public PerspectiveCamera camera;
private float width;
private float height;
public ModelBatch modelBatch;
public Model model;//create 500*5*500 floor
public Array<ModelInstance> instances;
public Array<ModelInstance> pipeinstances;
public Array<ModelInstance> toppipeinstances;
public Environment environment;
public CameraInputController camController;
ModelInstance playerinstance;
private int blockscale = 5;//pipe height max 65 or 75
private float pipespeed = 0.5f;
private Texture groundTexture;
private float gravity = -65.0f;
private float playerforce = 0.0f;
boolean collision;
private boolean touched;
private boolean dead;
//physics
btCollisionShape groundShape;
btCollisionShape ballShape;
btCollisionShape pipeShape;
btCollisionObject groundObject;
btCollisionObject ballObject;
btCollisionConfiguration collisionConfig;
btDispatcher dispatcher;
private Array<btCollisionObject> pipecollisions;
private Array<btCollisionObject> toppipecollisions;
Game g;
private Sound dieSound;
private Sound flopSound;
private Sound scoreSound;
private int score = 0;
public ClassicGameScreen(Game game){
g = game;
}
@Override
public void render(float delta) {
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(camera);
for (ModelInstance minstance : instances) {
modelBatch.render(minstance, environment);
}
for (int arrayint = 0; arrayint < pipeinstances.size; arrayint++){
if(touched && !dead){
pipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
pipecollisions.get(arrayint).setWorldTransform(pipeinstances.get(arrayint).transform);
collision = checkCollision(pipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(pipeinstances.get(arrayint), environment);
}
for (int arrayint = 0; arrayint < toppipeinstances.size; arrayint++) {
if(touched && !dead){
toppipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
toppipecollisions.get(arrayint).setWorldTransform(toppipeinstances.get(arrayint).transform);
collision = checkCollision(toppipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(toppipeinstances.get(arrayint), environment);
}
//check if pipes moved off screen.
Iterator<ModelInstance> iter = pipeinstances.iterator();
while(iter.hasNext()) {
ModelInstance pipe = iter.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
Vector3 playertmp = new Vector3();
playerinstance.transform.getTranslation(playertmp);
float playerx = playertmp.x;
if(x == 50*blockscale){//middle
spawnpipes(pipeinstances, toppipeinstances);
}
if(x == playerx){//add score
addscore();
}
if(x >= 60*blockscale){//left side
iter.remove();
}
}
Iterator<ModelInstance> iter2 = toppipeinstances.iterator();
while(iter2.hasNext()) {
ModelInstance pipe = iter2.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter2.remove();
}
}
Iterator<btCollisionObject> iter3 = pipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter3.hasNext()) {
btCollisionObject pipe = iter3.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter3.remove();
}
}
Iterator<btCollisionObject> iter4 = toppipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter4.hasNext()) {
btCollisionObject pipe = iter4.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter4.remove();
}
}
//player physics
if(!collision && touched && !dead){
//gravity
playerinstance.transform.translate(0, gravity*delta, 0);
//jumps
float playerforcetoapply = playerforce*delta*2;
playerforce-=playerforcetoapply;
if(playerforce<=0){
playerforce = 0.0f;
}
playerinstance.transform.translate(0, playerforcetoapply/2, 0);
ballObject.setWorldTransform(playerinstance.transform);
collision = checkCollision();
if(collision){
playerdie();
}
}
else if(touched && dead && collision){
playerinstance.transform.translate(0, gravity*delta, 0);
}
modelBatch.render(playerinstance, environment);
modelBatch.end();
}
private void addscore(){
score++;
scoreSound.play();
Gdx.app.log("score ", ""+score);
}
private void playerdie(){
//play sound and wait
dieSound.play();
dead = true;
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
Bullet.init();
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
camera = new PerspectiveCamera(67, 640*2, 480*2);
camera.position.set(50.0f*blockscale, 25.0f, 0.0f);
camera.lookAt(50.0f*blockscale, 25.0f, 50.0f*blockscale);
camera.near = 1f;
camera.far = 300f;
camera.update();
modelBatch = new ModelBatch();
instances = new Array<ModelInstance>();
pipeinstances = new Array<ModelInstance>();
toppipeinstances = new Array<ModelInstance>();
pipecollisions = new Array<btCollisionObject>();
toppipecollisions = new Array<btCollisionObject>();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f,
0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f,
-0.8f, -0.2f));
//environment.set(new ColorAttribute(ColorAttribute.Fog, 1f, 0.1f, 0.1f, 1.0f));
//physics
ballShape = new btSphereShape(4.0f);
pipeShape = new btCylinderShape(new Vector3(5.0f, 75.0f/2, 5.0f));
groundShape = new btBoxShape(new Vector3(50.0f*blockscale, 0.5f*blockscale, 50.0f*blockscale));
collisionConfig = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfig);
spawnfloor();
spawnpipes(pipeinstances, toppipeinstances);
spawnplayer();
groundObject = new btCollisionObject();
groundObject.setCollisionShape(groundShape);
groundObject.setWorldTransform(instances.peek().transform);
ballObject = new btCollisionObject();
ballObject.setCollisionShape(ballShape);
ballObject.setWorldTransform(playerinstance.transform);
//sounds
flopSound = Gdx.audio.newSound(Gdx.files.internal("sounds/switch.wav"));
dieSound = Gdx.audio.newSound(Gdx.files.internal("sounds/die.wav"));
scoreSound = Gdx.audio.newSound(Gdx.files.internal("sounds/point.wav"));
Gdx.input.setInputProcessor(this);
}
public void spawnfloor(){
groundTexture = new Texture("img/grass.png");
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
/*model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
TextureAttribute.createDiffuse(groundTexture)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);*/
model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
ColorAttribute.createDiffuse(Color.CLEAR)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(blockscale*50, -20.0f, blockscale*50);
instances.add(instance);
}
public void spawnCubeArray(Array<ModelInstance> cubeinstances){
for (int z = 0; z < 100; z++) {
for (int x = 0; x < 100; x++) {
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
if (x % 2 == 0) {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
else {
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
} else {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
else{
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
}
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(x * blockscale, 0, z*blockscale);
cubeinstances.add(instance);
}
}
}
public void spawnplayer(){
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(8.0f, 8.0f, 8.0f, 100, 100, new Material(ColorAttribute.createDiffuse(Color.MAROON)), Usage.Position | Usage.Normal);
playerinstance = new ModelInstance(model);
playerinstance.transform.translate(53.0f*blockscale, 40.0f, 10.0f*blockscale);
}
public void spawnpipes(Array<ModelInstance> pinstances, Array<ModelInstance> tinstances){
Random rn = new Random();
int random = rn.nextInt(29) + 1;
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
model = modelBuilder.createCylinder(10.0f, 75.0f, 10.0f, 100, new Material(
ColorAttribute.createDiffuse(Color.MAGENTA)), Usage.Position | Usage.Normal);
ModelInstance bottompipeinstance = new ModelInstance(model);
ModelInstance toppipeinstance = new ModelInstance(model);
bottompipeinstance.transform.translate(40.0f*blockscale, -5.0f-random, 10.0f*blockscale);
toppipeinstance.transform.translate(40.0f*blockscale, 95.0f-random, 10.0f*blockscale);
pinstances.add(bottompipeinstance);
tinstances.add(toppipeinstance);
btCollisionObject bottompipeObject = new btCollisionObject();
bottompipeObject.setCollisionShape(pipeShape);
bottompipeObject.setWorldTransform(bottompipeinstance.transform);
btCollisionObject toppipeObject = new btCollisionObject();
toppipeObject.setCollisionShape(pipeShape);
toppipeObject.setWorldTransform(toppipeinstance.transform);
pipecollisions.add(bottompipeObject);
toppipecollisions.add(toppipeObject);
}
private void jump(){
if(!touched)
touched=true;
if(!dead){
playerforce+=100.0f;
flopSound.play();
}
else {
g.setScreen(new ClassicGameScreen(g));
}
}
boolean checkCollision() {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(groundObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
boolean checkCollision(btCollisionObject colObject) {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(colObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
@Override
public void hide() {
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
model.dispose();
modelBatch.dispose();
groundTexture.dispose();
groundObject.dispose();
groundShape.dispose();
ballObject.dispose();
ballShape.dispose();
pipeShape.dispose();
dispatcher.dispose();
collisionConfig.dispose();
dieSound.dispose();
flopSound.dispose();
scoreSound.dispose();
this.dispose();
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.SPACE){
jump();
}
return false;
}
@Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
jump();
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
| Players can no longer go over top of pipes
| core/src/com/jtechapps/FloppyThreeD/Screens/ClassicGameScreen.java | Players can no longer go over top of pipes | <ide><path>ore/src/com/jtechapps/FloppyThreeD/Screens/ClassicGameScreen.java
<ide> if(collision){
<ide> playerdie();
<ide> }
<add> Vector3 playertmppos = new Vector3();
<add> playerinstance.transform.getTranslation(playertmppos);
<add> if(playertmppos.y >= 90){
<add> playerdie();
<add> }
<ide> }
<ide> else if(touched && dead && collision){
<ide> playerinstance.transform.translate(0, gravity*delta, 0); |
|
Java | apache-2.0 | c3755f15546cbd56935882bb6a179df3a2914f83 | 0 | lukeorland/joshua,fhieber/incubator-joshua,gwenniger/joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,kpu/joshua,gwenniger/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,kpu/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,kpu/joshua,fhieber/incubator-joshua,gwenniger/joshua,thammegowda/incubator-joshua,kpu/joshua,fhieber/incubator-joshua,lukeorland/joshua,lukeorland/joshua,lukeorland/joshua,fhieber/incubator-joshua,gwenniger/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,kpu/joshua,gwenniger/joshua,lukeorland/joshua,gwenniger/joshua,lukeorland/joshua,lukeorland/joshua,kpu/joshua | /* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
package joshua.decoder.ff;
import joshua.decoder.ff.tm.Rule;
/**
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate: 2008-07-28 18:44:45 -0400 (Mon, 28 Jul 2008) $
*/
public final class PhraseModelFF extends DefaultStatelessFF {
/* the feature will be activated only when the owner is the
* same as the rule, we need an owner to distinguish different
* feature in different phrase table/source
*/
private final int columnIndex; // = -1;//zero-indexed
public PhraseModelFF(final int feat_id_, final double weight_, final int owner_, final int column_index) {
super(weight_, owner_, feat_id_);
this.columnIndex = column_index;
}
public double estimate(final Rule rule) {
//Support.write_log_line("model owner: " + owner + "; rule owner: "+r.owner, Support.INFO);
if (this.owner == rule.owner) {
if (this.columnIndex < rule.feat_scores.length) {
return rule.feat_scores[this.columnIndex];
} else {
System.out.println("In PhraseModelFF: columnIndex is not right, model columnIndex: " + columnIndex + "; rule is: " + rule.toString());
System.exit(0);
return 0.0;
}
} else {
return 0.0;
}
}
}
| src/joshua/decoder/ff/PhraseModelFF.java | /* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
package joshua.decoder.ff;
import joshua.decoder.ff.tm.Rule;
/**
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate: 2008-07-28 18:44:45 -0400 (Mon, 28 Jul 2008) $
*/
public final class PhraseModelFF extends DefaultStatelessFF {
/* the feature will be activated only when the owner is the
* same as the rule, we need an owner to distinguish different
* feature in different phrase table/source
*/
private final int columnIndex; // = -1;//zero-indexed
public PhraseModelFF(final int feat_id_, final double weight_, final int owner_, final int column_index) {
super(weight_, owner_, feat_id_);
this.columnIndex = column_index;
}
public double estimate(final Rule rule) {
//Support.write_log_line("model owner: " + owner + "; rule owner: "+r.owner, Support.INFO);
if (this.owner == rule.owner) {
if (this.columnIndex < rule.feat_scores.length) {
return rule.feat_scores[this.columnIndex];
} else {
System.out.println("In PhraseModelFF: columnIndex is not right, model columnIndex: " + columnIndex + "; max colum in rule: rule.feat_scores.length");
System.exit(0);
return 0.0;
}
} else {
return 0.0;
}
}
}
| add debug info
git-svn-id: 113d22c177a5f4646d60eedc1d71f196641d30ff@313 0ae5e6b2-d358-4f09-a895-f82f13dd62a4
| src/joshua/decoder/ff/PhraseModelFF.java | add debug info | <ide><path>rc/joshua/decoder/ff/PhraseModelFF.java
<ide> if (this.columnIndex < rule.feat_scores.length) {
<ide> return rule.feat_scores[this.columnIndex];
<ide> } else {
<del> System.out.println("In PhraseModelFF: columnIndex is not right, model columnIndex: " + columnIndex + "; max colum in rule: rule.feat_scores.length");
<add> System.out.println("In PhraseModelFF: columnIndex is not right, model columnIndex: " + columnIndex + "; rule is: " + rule.toString());
<ide> System.exit(0);
<ide> return 0.0;
<ide> } |
|
Java | apache-2.0 | 0f1fc65bd595b55e81639f96378c532820e0b441 | 0 | a1vanov/ignite,psadusumilli/ignite,endian675/ignite,dlnufox/ignite,amirakhmedov/ignite,ntikhonov/ignite,dmagda/incubator-ignite,kromulan/ignite,NSAmelchev/ignite,a1vanov/ignite,ilantukh/ignite,pperalta/ignite,ryanzz/ignite,arijitt/incubator-ignite,alexzaitzev/ignite,afinka77/ignite,ilantukh/ignite,kidaa/incubator-ignite,psadusumilli/ignite,nivanov/ignite,wmz7year/ignite,shurun19851206/ignite,psadusumilli/ignite,agoncharuk/ignite,shroman/ignite,sylentprayer/ignite,alexzaitzev/ignite,iveselovskiy/ignite,xtern/ignite,kromulan/ignite,daradurvs/ignite,zzcclp/ignite,andrey-kuznetsov/ignite,apache/ignite,gridgain/apache-ignite,dlnufox/ignite,vsuslov/incubator-ignite,VladimirErshov/ignite,shroman/ignite,pperalta/ignite,avinogradovgg/ignite,VladimirErshov/ignite,dlnufox/ignite,abhishek-ch/incubator-ignite,a1vanov/ignite,zzcclp/ignite,thuTom/ignite,StalkXT/ignite,StalkXT/ignite,svladykin/ignite,chandresh-pancholi/ignite,rfqu/ignite,nizhikov/ignite,sylentprayer/ignite,NSAmelchev/ignite,avinogradovgg/ignite,samaitra/ignite,apacheignite/ignite,samaitra/ignite,chandresh-pancholi/ignite,shurun19851206/ignite,nizhikov/ignite,mcherkasov/ignite,gargvish/ignite,irudyak/ignite,murador/ignite,arijitt/incubator-ignite,louishust/incubator-ignite,vadopolski/ignite,wmz7year/ignite,wmz7year/ignite,wmz7year/ignite,samaitra/ignite,nizhikov/ignite,daradurvs/ignite,DoudTechData/ignite,murador/ignite,pperalta/ignite,xtern/ignite,vsisko/incubator-ignite,rfqu/ignite,rfqu/ignite,BiryukovVA/ignite,amirakhmedov/ignite,zzcclp/ignite,SomeFire/ignite,BiryukovVA/ignite,voipp/ignite,xtern/ignite,agura/incubator-ignite,SharplEr/ignite,thuTom/ignite,murador/ignite,ptupitsyn/ignite,vldpyatkov/ignite,pperalta/ignite,akuznetsov-gridgain/ignite,chandresh-pancholi/ignite,louishust/incubator-ignite,rfqu/ignite,NSAmelchev/ignite,kidaa/incubator-ignite,xtern/ignite,agura/incubator-ignite,NSAmelchev/ignite,ptupitsyn/ignite,svladykin/ignite,sylentprayer/ignite,apache/ignite,f7753/ignite,tkpanther/ignite,shroman/ignite,vsisko/incubator-ignite,mcherkasov/ignite,amirakhmedov/ignite,vladisav/ignite,ascherbakoff/ignite,svladykin/ignite,tkpanther/ignite,vldpyatkov/ignite,BiryukovVA/ignite,murador/ignite,abhishek-ch/incubator-ignite,shroman/ignite,avinogradovgg/ignite,agoncharuk/ignite,mcherkasov/ignite,ntikhonov/ignite,nizhikov/ignite,irudyak/ignite,adeelmahmood/ignite,kromulan/ignite,WilliamDo/ignite,ascherbakoff/ignite,kromulan/ignite,SharplEr/ignite,vsuslov/incubator-ignite,vsisko/incubator-ignite,a1vanov/ignite,afinka77/ignite,shroman/ignite,vldpyatkov/ignite,apache/ignite,VladimirErshov/ignite,vladisav/ignite,gargvish/ignite,SharplEr/ignite,andrey-kuznetsov/ignite,agoncharuk/ignite,alexzaitzev/ignite,dream-x/ignite,NSAmelchev/ignite,sylentprayer/ignite,shroman/ignite,apache/ignite,agura/incubator-ignite,thuTom/ignite,ilantukh/ignite,SharplEr/ignite,arijitt/incubator-ignite,iveselovskiy/ignite,rfqu/ignite,shurun19851206/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,dream-x/ignite,gargvish/ignite,shroman/ignite,adeelmahmood/ignite,shurun19851206/ignite,StalkXT/ignite,VladimirErshov/ignite,gargvish/ignite,wmz7year/ignite,agura/incubator-ignite,wmz7year/ignite,DoudTechData/ignite,abhishek-ch/incubator-ignite,vsisko/incubator-ignite,StalkXT/ignite,gargvish/ignite,kidaa/incubator-ignite,murador/ignite,apacheignite/ignite,afinka77/ignite,ptupitsyn/ignite,murador/ignite,daradurvs/ignite,voipp/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,voipp/ignite,svladykin/ignite,louishust/incubator-ignite,ryanzz/ignite,pperalta/ignite,andrey-kuznetsov/ignite,dream-x/ignite,adeelmahmood/ignite,shroman/ignite,VladimirErshov/ignite,dmagda/incubator-ignite,StalkXT/ignite,SomeFire/ignite,ntikhonov/ignite,akuznetsov-gridgain/ignite,apache/ignite,adeelmahmood/ignite,voipp/ignite,andrey-kuznetsov/ignite,ilantukh/ignite,SomeFire/ignite,ascherbakoff/ignite,f7753/ignite,nivanov/ignite,daradurvs/ignite,apacheignite/ignite,shroman/ignite,WilliamDo/ignite,nizhikov/ignite,gridgain/apache-ignite,WilliamDo/ignite,endian675/ignite,ilantukh/ignite,voipp/ignite,vadopolski/ignite,iveselovskiy/ignite,tkpanther/ignite,svladykin/ignite,DoudTechData/ignite,sk0x50/ignite,gridgain/apache-ignite,avinogradovgg/ignite,wmz7year/ignite,ashutakGG/incubator-ignite,psadusumilli/ignite,amirakhmedov/ignite,louishust/incubator-ignite,sk0x50/ignite,dlnufox/ignite,tkpanther/ignite,ilantukh/ignite,samaitra/ignite,vadopolski/ignite,tkpanther/ignite,sk0x50/ignite,DoudTechData/ignite,amirakhmedov/ignite,irudyak/ignite,adeelmahmood/ignite,ashutakGG/incubator-ignite,sk0x50/ignite,NSAmelchev/ignite,samaitra/ignite,BiryukovVA/ignite,vladisav/ignite,zzcclp/ignite,dmagda/incubator-ignite,leveyj/ignite,tkpanther/ignite,iveselovskiy/ignite,akuznetsov-gridgain/ignite,abhishek-ch/incubator-ignite,SomeFire/ignite,avinogradovgg/ignite,ptupitsyn/ignite,daradurvs/ignite,f7753/ignite,mcherkasov/ignite,apacheignite/ignite,SharplEr/ignite,gargvish/ignite,ryanzz/ignite,voipp/ignite,WilliamDo/ignite,mcherkasov/ignite,agoncharuk/ignite,endian675/ignite,ptupitsyn/ignite,StalkXT/ignite,gargvish/ignite,irudyak/ignite,dmagda/incubator-ignite,agura/incubator-ignite,louishust/incubator-ignite,kromulan/ignite,amirakhmedov/ignite,amirakhmedov/ignite,sylentprayer/ignite,a1vanov/ignite,svladykin/ignite,voipp/ignite,shurun19851206/ignite,zzcclp/ignite,amirakhmedov/ignite,ntikhonov/ignite,nivanov/ignite,endian675/ignite,nivanov/ignite,tkpanther/ignite,gargvish/ignite,kidaa/incubator-ignite,agoncharuk/ignite,mcherkasov/ignite,dmagda/incubator-ignite,nizhikov/ignite,nivanov/ignite,abhishek-ch/incubator-ignite,vadopolski/ignite,ilantukh/ignite,gridgain/apache-ignite,ascherbakoff/ignite,vadopolski/ignite,samaitra/ignite,xtern/ignite,vldpyatkov/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,kidaa/incubator-ignite,apache/ignite,daradurvs/ignite,ntikhonov/ignite,avinogradovgg/ignite,andrey-kuznetsov/ignite,ntikhonov/ignite,samaitra/ignite,dlnufox/ignite,vadopolski/ignite,nizhikov/ignite,dmagda/incubator-ignite,agoncharuk/ignite,alexzaitzev/ignite,iveselovskiy/ignite,VladimirErshov/ignite,sk0x50/ignite,vladisav/ignite,kromulan/ignite,daradurvs/ignite,kidaa/incubator-ignite,agura/incubator-ignite,ntikhonov/ignite,endian675/ignite,DoudTechData/ignite,irudyak/ignite,thuTom/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,adeelmahmood/ignite,shroman/ignite,vsuslov/incubator-ignite,vsisko/incubator-ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,rfqu/ignite,BiryukovVA/ignite,daradurvs/ignite,dmagda/incubator-ignite,sk0x50/ignite,dream-x/ignite,wmz7year/ignite,WilliamDo/ignite,ryanzz/ignite,adeelmahmood/ignite,vadopolski/ignite,BiryukovVA/ignite,ptupitsyn/ignite,SharplEr/ignite,samaitra/ignite,vladisav/ignite,vldpyatkov/ignite,rfqu/ignite,voipp/ignite,murador/ignite,leveyj/ignite,leveyj/ignite,DoudTechData/ignite,f7753/ignite,avinogradovgg/ignite,endian675/ignite,akuznetsov-gridgain/ignite,ptupitsyn/ignite,gridgain/apache-ignite,murador/ignite,vsisko/incubator-ignite,irudyak/ignite,mcherkasov/ignite,WilliamDo/ignite,svladykin/ignite,daradurvs/ignite,ryanzz/ignite,DoudTechData/ignite,chandresh-pancholi/ignite,thuTom/ignite,vladisav/ignite,louishust/incubator-ignite,pperalta/ignite,dream-x/ignite,xtern/ignite,psadusumilli/ignite,pperalta/ignite,dlnufox/ignite,thuTom/ignite,vladisav/ignite,shurun19851206/ignite,thuTom/ignite,ryanzz/ignite,iveselovskiy/ignite,amirakhmedov/ignite,ashutakGG/incubator-ignite,vsuslov/incubator-ignite,sylentprayer/ignite,SomeFire/ignite,psadusumilli/ignite,alexzaitzev/ignite,dream-x/ignite,arijitt/incubator-ignite,f7753/ignite,ryanzz/ignite,BiryukovVA/ignite,ptupitsyn/ignite,nizhikov/ignite,ptupitsyn/ignite,nizhikov/ignite,zzcclp/ignite,ashutakGG/incubator-ignite,f7753/ignite,xtern/ignite,daradurvs/ignite,ascherbakoff/ignite,dmagda/incubator-ignite,sylentprayer/ignite,zzcclp/ignite,arijitt/incubator-ignite,a1vanov/ignite,ilantukh/ignite,vsisko/incubator-ignite,vsuslov/incubator-ignite,NSAmelchev/ignite,vladisav/ignite,leveyj/ignite,SomeFire/ignite,StalkXT/ignite,apacheignite/ignite,sk0x50/ignite,afinka77/ignite,vsisko/incubator-ignite,kromulan/ignite,dream-x/ignite,leveyj/ignite,vldpyatkov/ignite,irudyak/ignite,afinka77/ignite,apacheignite/ignite,sk0x50/ignite,psadusumilli/ignite,leveyj/ignite,thuTom/ignite,arijitt/incubator-ignite,BiryukovVA/ignite,nivanov/ignite,alexzaitzev/ignite,shurun19851206/ignite,agoncharuk/ignite,vldpyatkov/ignite,akuznetsov-gridgain/ignite,DoudTechData/ignite,ptupitsyn/ignite,samaitra/ignite,ashutakGG/incubator-ignite,ntikhonov/ignite,a1vanov/ignite,samaitra/ignite,afinka77/ignite,andrey-kuznetsov/ignite,adeelmahmood/ignite,vldpyatkov/ignite,abhishek-ch/incubator-ignite,endian675/ignite,BiryukovVA/ignite,SharplEr/ignite,VladimirErshov/ignite,afinka77/ignite,xtern/ignite,SharplEr/ignite,StalkXT/ignite,NSAmelchev/ignite,voipp/ignite,xtern/ignite,ascherbakoff/ignite,f7753/ignite,ryanzz/ignite,agura/incubator-ignite,sylentprayer/ignite,ascherbakoff/ignite,tkpanther/ignite,StalkXT/ignite,shurun19851206/ignite,WilliamDo/ignite,gridgain/apache-ignite,dlnufox/ignite,mcherkasov/ignite,gridgain/apache-ignite,SomeFire/ignite,rfqu/ignite,a1vanov/ignite,zzcclp/ignite,SharplEr/ignite,SomeFire/ignite,vsuslov/incubator-ignite,andrey-kuznetsov/ignite,apache/ignite,SomeFire/ignite,apacheignite/ignite,alexzaitzev/ignite,pperalta/ignite,WilliamDo/ignite,leveyj/ignite,chandresh-pancholi/ignite,agoncharuk/ignite,NSAmelchev/ignite,nivanov/ignite,sk0x50/ignite,ashutakGG/incubator-ignite,SomeFire/ignite,alexzaitzev/ignite,irudyak/ignite,kromulan/ignite,nivanov/ignite,irudyak/ignite,afinka77/ignite,VladimirErshov/ignite,dream-x/ignite,ilantukh/ignite,endian675/ignite,leveyj/ignite,ascherbakoff/ignite,apache/ignite,ilantukh/ignite,f7753/ignite,akuznetsov-gridgain/ignite,alexzaitzev/ignite,apache/ignite,vadopolski/ignite,apacheignite/ignite,dlnufox/ignite,agura/incubator-ignite | /*
* 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.ignite.internal.processors.cache.integration;
import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.store.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.resources.*;
import org.jetbrains.annotations.*;
import javax.cache.*;
import javax.cache.configuration.*;
import javax.cache.integration.*;
import java.util.*;
import java.util.concurrent.*;
import static org.apache.ignite.cache.CacheDistributionMode.*;
/**
*
*/
public abstract class IgniteCacheStoreSessionWriteBehindAbstractTest extends IgniteCacheAbstractTest {
/** */
private static final String CACHE_NAME1 = "cache1";
/** */
private static volatile CountDownLatch latch;
/** */
private static volatile ExpectedData expData;
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return CacheMode.PARTITIONED;
}
/** {@inheritDoc} */
@Override protected CacheDistributionMode distributionMode() {
return PARTITIONED_ONLY;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
assert cfg.getCacheConfiguration().length == 1;
CacheConfiguration ccfg0 = cfg.getCacheConfiguration()[0];
ccfg0.setReadThrough(true);
ccfg0.setWriteThrough(true);
ccfg0.setWriteBehindBatchSize(10);
ccfg0.setWriteBehindFlushSize(10);
ccfg0.setWriteBehindFlushFrequency(60_000);
ccfg0.setWriteBehindEnabled(true);
ccfg0.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new TestStore()));
CacheConfiguration ccfg1 = cacheConfiguration(gridName);
ccfg1.setReadThrough(true);
ccfg1.setWriteThrough(true);
ccfg1.setWriteBehindBatchSize(10);
ccfg1.setWriteBehindFlushSize(10);
ccfg1.setWriteBehindFlushFrequency(60_000);
ccfg1.setWriteBehindEnabled(true);
ccfg1.setName(CACHE_NAME1);
ccfg1.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new TestStore()));
cfg.setCacheConfiguration(ccfg0, ccfg1);
return cfg;
}
/**
* @throws Exception If failed.
*/
public void testSession() throws Exception {
testCache(null);
testCache(CACHE_NAME1);
}
/**
* @param cacheName Cache name.
* @throws Exception If failed.
*/
private void testCache(String cacheName) throws Exception {
IgniteCache<Integer, Integer> cache = ignite(0).jcache(cacheName);
try {
latch = new CountDownLatch(2);
expData = new ExpectedData("writeAll", cacheName);
for (int i = 0; i < 11; i++)
cache.put(i, i);
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
}
finally {
latch = null;
}
try {
latch = new CountDownLatch(2);
expData = new ExpectedData("deleteAll", cacheName);
for (int i = 0; i < 11; i++)
cache.remove(i);
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
}
finally {
latch = null;
}
}
/**
*
*/
private class TestStore implements CacheStore<Object, Object> {
/** Auto-injected store session. */
@CacheStoreSessionResource
private CacheStoreSession ses;
/** */
@IgniteInstanceResource
protected Ignite ignite;
/** {@inheritDoc} */
@Override public void loadCache(IgniteBiInClosure<Object, Object> clo, @Nullable Object... args) {
fail();
}
/** {@inheritDoc} */
@Override public void txEnd(boolean commit) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public Object load(Object key) throws CacheLoaderException {
fail();
return null;
}
/** {@inheritDoc} */
@Override public Map<Object, Object> loadAll(Iterable<?> keys) throws CacheLoaderException {
fail();
return null;
}
/** {@inheritDoc} */
@Override public void write(Cache.Entry<?, ?> entry) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public void writeAll(Collection<Cache.Entry<?, ?>> entries) throws CacheWriterException {
log.info("writeAll: " + entries);
assertTrue("Unexpected entries: " + entries, entries.size() == 10 || entries.size() == 1);
checkSession("writeAll");
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public void deleteAll(Collection<?> keys) throws CacheWriterException {
log.info("deleteAll: " + keys);
assertTrue("Unexpected keys: " + keys, keys.size() == 10 || keys.size() == 1);
checkSession("deleteAll");
}
/**
* @return Store session.
*/
private CacheStoreSession session() {
return ses;
}
/**
* @param mtd Called stored method.
*/
private void checkSession(String mtd) {
assertNotNull(ignite);
CacheStoreSession ses = session();
assertNotNull(ses);
log.info("Cache: " + ses.cacheName());
assertFalse(ses.isWithinTransaction());
assertNull(ses.transaction());
assertNotNull(expData);
assertEquals(mtd, expData.expMtd);
assertEquals(expData.expCacheName, ses.cacheName());
assertNotNull(ses.properties());
ses.properties().put(1, "test");
assertEquals("test", ses.properties().get(1));
latch.countDown();
}
}
/**
*
*/
static class ExpectedData {
/** */
private final String expMtd;
/** */
private final String expCacheName;
/**
* @param expMtd Expected method.
* @param expCacheName Expected cache name.
*/
public ExpectedData(String expMtd, String expCacheName) {
this.expMtd = expMtd;
this.expCacheName = expCacheName;
}
}
}
| modules/core/src/test/java/org/apache/ignite/internal/processors/cache/integration/IgniteCacheStoreSessionWriteBehindAbstractTest.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.ignite.internal.processors.cache.integration;
import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.store.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.resources.*;
import org.jetbrains.annotations.*;
import javax.cache.*;
import javax.cache.configuration.*;
import javax.cache.integration.*;
import java.util.*;
import java.util.concurrent.*;
import static org.apache.ignite.cache.CacheDistributionMode.*;
/**
*
*/
public abstract class IgniteCacheStoreSessionWriteBehindAbstractTest extends IgniteCacheAbstractTest {
/** */
private static final String CACHE_NAME1 = "cache1";
/** */
private static volatile CountDownLatch latch;
/** */
private static volatile ExpectedData expData;
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return CacheMode.PARTITIONED;
}
/** {@inheritDoc} */
@Override protected CacheDistributionMode distributionMode() {
return PARTITIONED_ONLY;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
assert cfg.getCacheConfiguration().length == 1;
CacheConfiguration ccfg0 = cfg.getCacheConfiguration()[0];
ccfg0.setReadThrough(true);
ccfg0.setWriteThrough(true);
ccfg0.setWriteBehindBatchSize(10);
ccfg0.setWriteBehindFlushSize(10);
ccfg0.setWriteBehindFlushFrequency(5000);
ccfg0.setWriteBehindEnabled(true);
ccfg0.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new TestStore()));
CacheConfiguration ccfg1 = cacheConfiguration(gridName);
ccfg1.setReadThrough(true);
ccfg1.setWriteThrough(true);
ccfg1.setWriteBehindBatchSize(10);
ccfg1.setWriteBehindFlushSize(10);
ccfg1.setWriteBehindFlushFrequency(5000);
ccfg1.setWriteBehindEnabled(true);
ccfg1.setName(CACHE_NAME1);
ccfg1.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new TestStore()));
cfg.setCacheConfiguration(ccfg0, ccfg1);
return cfg;
}
/**
* @throws Exception If failed.
*/
public void testSession() throws Exception {
testCache(null);
testCache(CACHE_NAME1);
}
/**
* @param cacheName Cache name.
* @throws Exception If failed.
*/
private void testCache(String cacheName) throws Exception {
IgniteCache<Integer, Integer> cache = ignite(0).jcache(cacheName);
try {
latch = new CountDownLatch(1);
expData = new ExpectedData("writeAll", cacheName);
for (int i = 0; i < 10; i++)
cache.put(i, i);
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
}
finally {
latch = null;
}
try {
latch = new CountDownLatch(1);
expData = new ExpectedData("deleteAll", cacheName);
for (int i = 0; i < 10; i++)
cache.remove(i);
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
}
finally {
latch = null;
}
}
/**
*
*/
private class TestStore implements CacheStore<Object, Object> {
/** Auto-injected store session. */
@CacheStoreSessionResource
private CacheStoreSession ses;
/** */
@IgniteInstanceResource
protected Ignite ignite;
/** {@inheritDoc} */
@Override public void loadCache(IgniteBiInClosure<Object, Object> clo, @Nullable Object... args) {
fail();
}
/** {@inheritDoc} */
@Override public void txEnd(boolean commit) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public Object load(Object key) throws CacheLoaderException {
fail();
return null;
}
/** {@inheritDoc} */
@Override public Map<Object, Object> loadAll(Iterable<?> keys) throws CacheLoaderException {
fail();
return null;
}
/** {@inheritDoc} */
@Override public void write(Cache.Entry<?, ?> entry) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public void writeAll(Collection<Cache.Entry<?, ?>> entries) throws CacheWriterException {
log.info("writeAll: " + entries);
assertEquals(10, entries.size());
checkSession("writeAll");
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
fail();
}
/** {@inheritDoc} */
@Override public void deleteAll(Collection<?> keys) throws CacheWriterException {
log.info("deleteAll: " + keys);
assertEquals(10, keys.size());
checkSession("deleteAll");
}
/**
* @return Store session.
*/
private CacheStoreSession session() {
return ses;
}
/**
* @param mtd Called stored method.
*/
private void checkSession(String mtd) {
assertNotNull(ignite);
CacheStoreSession ses = session();
assertNotNull(ses);
log.info("Cache: " + ses.cacheName());
assertFalse(ses.isWithinTransaction());
assertNull(ses.transaction());
assertNotNull(expData);
assertEquals(mtd, expData.expMtd);
assertEquals(expData.expCacheName, ses.cacheName());
assertNotNull(ses.properties());
ses.properties().put(1, "test");
assertEquals("test", ses.properties().get(1));
latch.countDown();
}
}
/**
*
*/
static class ExpectedData {
/** */
private final String expMtd;
/** */
private final String expCacheName;
/**
* @param expMtd Expected method.
* @param expCacheName Expected cache name.
*/
public ExpectedData(String expMtd, String expCacheName) {
this.expMtd = expMtd;
this.expCacheName = expCacheName;
}
}
}
| # sprint-2 fixed test
| modules/core/src/test/java/org/apache/ignite/internal/processors/cache/integration/IgniteCacheStoreSessionWriteBehindAbstractTest.java | # sprint-2 fixed test | <ide><path>odules/core/src/test/java/org/apache/ignite/internal/processors/cache/integration/IgniteCacheStoreSessionWriteBehindAbstractTest.java
<ide> ccfg0.setWriteThrough(true);
<ide> ccfg0.setWriteBehindBatchSize(10);
<ide> ccfg0.setWriteBehindFlushSize(10);
<del> ccfg0.setWriteBehindFlushFrequency(5000);
<add> ccfg0.setWriteBehindFlushFrequency(60_000);
<ide> ccfg0.setWriteBehindEnabled(true);
<ide>
<ide> ccfg0.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new TestStore()));
<ide> ccfg1.setWriteThrough(true);
<ide> ccfg1.setWriteBehindBatchSize(10);
<ide> ccfg1.setWriteBehindFlushSize(10);
<del> ccfg1.setWriteBehindFlushFrequency(5000);
<add> ccfg1.setWriteBehindFlushFrequency(60_000);
<ide> ccfg1.setWriteBehindEnabled(true);
<ide>
<ide> ccfg1.setName(CACHE_NAME1);
<ide> IgniteCache<Integer, Integer> cache = ignite(0).jcache(cacheName);
<ide>
<ide> try {
<del> latch = new CountDownLatch(1);
<add> latch = new CountDownLatch(2);
<ide>
<ide> expData = new ExpectedData("writeAll", cacheName);
<ide>
<del> for (int i = 0; i < 10; i++)
<add> for (int i = 0; i < 11; i++)
<ide> cache.put(i, i);
<ide>
<ide> assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
<ide> }
<ide>
<ide> try {
<del> latch = new CountDownLatch(1);
<add> latch = new CountDownLatch(2);
<ide>
<ide> expData = new ExpectedData("deleteAll", cacheName);
<ide>
<del> for (int i = 0; i < 10; i++)
<add> for (int i = 0; i < 11; i++)
<ide> cache.remove(i);
<ide>
<ide> assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
<ide> @Override public void writeAll(Collection<Cache.Entry<?, ?>> entries) throws CacheWriterException {
<ide> log.info("writeAll: " + entries);
<ide>
<del> assertEquals(10, entries.size());
<add> assertTrue("Unexpected entries: " + entries, entries.size() == 10 || entries.size() == 1);
<ide>
<ide> checkSession("writeAll");
<ide> }
<ide> @Override public void deleteAll(Collection<?> keys) throws CacheWriterException {
<ide> log.info("deleteAll: " + keys);
<ide>
<del> assertEquals(10, keys.size());
<add> assertTrue("Unexpected keys: " + keys, keys.size() == 10 || keys.size() == 1);
<ide>
<ide> checkSession("deleteAll");
<ide> } |
|
Java | agpl-3.0 | fe65b09ea27d3f2b131d243ab70e6a670eee1c43 | 0 | acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 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 General Public License
* as published by the Free Software Foundation; either version
* 2 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.config.PAProperties;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
/**
* @author Arnaud Contes
*
* This class stores all logger used in ProActive. It provides an easy way
* to create and to retrieve a logger.
*/
public class ProActiveLogger extends Logger {
static {
if (System.getProperty("log4j.configuration") == null) {
// if logger is not defined create default logger with level info that logs
// on the console
File f = new File(System.getProperty("user.home") + File.separator + Constants.USER_CONFIG_DIR +
File.separator + ProActiveConfiguration.PROACTIVE_LOG_PROPERTIES_FILE);
if (f.exists()) {
try {
InputStream in = new FileInputStream(f);
// testing the availability of the file
Properties p = new Properties();
p.load(in);
PropertyConfigurator.configure(p);
System.setProperty("log4j.configuration", f.toURI().toString());
} catch (Exception e) {
System.err.println("the user's log4j configuration file (" + f.getAbsolutePath() +
") exits but is not accessible, fallbacking on the default configuration");
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private static ProActiveLoggerFactory myFactory = new ProActiveLoggerFactory();
/**
Just calls the parent constructor.
*/
protected ProActiveLogger(String name) {
super(name);
}
/**
This method overrides {@link Logger#getLogger} by supplying
its own factory type as a parameter.
*/
public static Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
/**
* Get corresponding stack trace as string
* @param e A Throwable
* @return The output of printStackTrace is returned as a String
*/
public static String getStackTraceAsString(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
}
| src/Core/org/objectweb/proactive/core/util/log/ProActiveLogger.java | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 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 General Public License
* as published by the Free Software Foundation; either version
* 2 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.config.PAProperties;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
/**
* @author Arnaud Contes
*
* This class stores all logger used in proactive. It provides an easy way
* to create and to retrieve a logger.
*/
public class ProActiveLogger extends Logger {
static {
if (System.getProperty("log4j.configuration") == null) {
// if logger is not defined create default logger with level info that logs
// on the console
File f = new File(System.getProperty("user.home") + File.separator + Constants.USER_CONFIG_DIR +
File.separator + ProActiveConfiguration.PROACTIVE_LOG_PROPERTIES_FILE);
if (f.exists()) {
try {
InputStream in = new FileInputStream(f);
// testing the availability of the file
Properties p = new Properties();
p.load(in);
PropertyConfigurator.configure(p);
System.setProperty("log4j.configuration", f.toURI().toString());
} catch (Exception e) {
System.err.println("the user's log4j configuration file (" + f.getAbsolutePath() +
") exits but is not accessible, fallbacking on the default configuration");
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private static ProActiveLoggerFactory myFactory = new ProActiveLoggerFactory();
/**
Just calls the parent constructor.
*/
protected ProActiveLogger(String name) {
super(name);
}
/**
This method overrides {@link Logger#getLogger} by supplying
its own factory type as a parameter.
*/
public static Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
/**
* Get corresponding stack trace as string
* @param e A Throwable
* @return The output of printStackTrace is returned as a String
*/
public static String getStackTraceAsString(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
}
| fix text typo
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@7862 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/Core/org/objectweb/proactive/core/util/log/ProActiveLogger.java | fix text typo | <ide><path>rc/Core/org/objectweb/proactive/core/util/log/ProActiveLogger.java
<ide> /**
<ide> * @author Arnaud Contes
<ide> *
<del> * This class stores all logger used in proactive. It provides an easy way
<add> * This class stores all logger used in ProActive. It provides an easy way
<ide> * to create and to retrieve a logger.
<ide> */
<ide> public class ProActiveLogger extends Logger { |
|
Java | mit | aa44e923fef64dd0a39480bd8e08ebe47bf5f7d8 | 0 | napstr/SqlSauce | /*
* MIT License
*
* Copyright (c) 2017 Dennis Neufeld
*
* 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 space.npstr.sqlsauce;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.metrics.MetricsTrackerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.prometheus.client.hibernate.HibernateStatisticsCollector;
import net.ttddyy.dsproxy.support.ProxyDataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.flywaydb.core.Flyway;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.entities.SaucedEntity;
import space.npstr.sqlsauce.ssh.SshTunnel;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by napster on 29.05.17.
* <p>
* Connection to a database through an optional SSH tunnel
*/
public class DatabaseConnection {
private static final Logger log = LoggerFactory.getLogger(DatabaseConnection.class);
private static final String TEST_QUERY = "SELECT 1;";
private static final long DEFAULT_FORCE_RECONNECT_TUNNEL_AFTER = TimeUnit.MINUTES.toNanos(1);
private final EntityManagerFactory emf;
private final HikariDataSource hikariDataSource;
@Nullable
private final ProxyDataSource proxiedDataSource;
@Nullable
private SshTunnel sshTunnel = null;
private final String dbName; //a comprehensible name for this connection
private volatile DatabaseState state = DatabaseState.UNINITIALIZED;
@Nullable
private final ScheduledExecutorService connectionCheck;
private final long tunnelForceReconnectAfter;
private long lastConnected;
/**
* @param dbName name for this database connection, also used as the persistence unit name and other
* places. Make sure it is unique across your application for best results.
* @param jdbcUrl where to find the db, which user, which pw, etc; see easy to find jdbc url docs on the web
* @param dataSourceProps properties for the underlying data source. see {@link Builder#getDefaultDataSourceProps()} for a start
* @param hikariConfig config for hikari. see {@link Builder#getDefaultHikariConfig()} ()} for a start
* @param hibernateProps properties for hibernate. see {@link Builder#getDefaultHibernateProps()} ()} for a start
* @param entityPackages example: "space.npstr.wolfia.db.entity", the names of the packages containing your
* annotated entities. root package names are fine, they will pick up all children
* @param poolName optional name for the connection pool; if null, a default name based on the db name will be picked
* @param sshDetails optionally ssh tunnel the connection; highly recommended for all remote databases
* @param hibernateStats optional metrics for hibernate. make sure to register it after adding all connections to it
* @param hikariStats optional metrics for hikari
* @param checkConnection set to false to disable a periodic healthcheck and automatic reconnection of the connection.
* only recommended if you run your own healthcheck and reconnection logic
* @param tunnelForceReconnectAfter (nanos) will forcefully reconnect a connected tunnel as part of the
* healthcheck, if there was no successful test query for this time period.
* @param proxyDataSourceBuilder optional datasource proxy that is useful for logging and intercepting queries, see
* https://github.com/ttddyy/datasource-proxy. The hikari datasource will be set on it,
* and the resulting proxy will be passed to hibernate.
* @param flyway optional Flyway migrations. This constructor will call Flyway#setDataSource and
* Flyway#migrate() after creating the ssh tunnel and hikari datasource, and before handing
* the datasource over to the datasource proxy and hibernate. If you need tighter control
* over the handling of migrations, consider running them manually before creating the
* DatabaseConnection. Flyway supports the use of a jdbcUrl instead of a datasource, and
* you can also manually build a temporary ssh tunnel if need be.
*/
public DatabaseConnection(final String dbName,
final String jdbcUrl,
final Properties dataSourceProps,
final HikariConfig hikariConfig,
final Properties hibernateProps,
final Collection<String> entityPackages,
@Nullable final String poolName,
@Nullable final SshTunnel.SshDetails sshDetails,
@Nullable final MetricsTrackerFactory hikariStats,
@Nullable final HibernateStatisticsCollector hibernateStats,
final boolean checkConnection,
long tunnelForceReconnectAfter,
@Nullable final ProxyDataSourceBuilder proxyDataSourceBuilder,
@Nullable final Flyway flyway) throws DatabaseException {
this.dbName = dbName;
this.state = DatabaseState.INITIALIZING;
this.tunnelForceReconnectAfter = tunnelForceReconnectAfter;
try {
// create ssh tunnel
if (sshDetails != null) {
this.sshTunnel = new SshTunnel(sshDetails).connect();
lastConnected = System.nanoTime();
}
// hikari connection pool
final HikariConfig hiConf = new HikariConfig();
hikariConfig.copyStateTo(hiConf); //dont touch the provided config, it might get reused outside, instead use a copy
hiConf.setJdbcUrl(jdbcUrl);
if (poolName != null && !poolName.isEmpty()) {
hiConf.setPoolName(poolName);
} else {
hiConf.setPoolName(dbName + "-DefaultPool");
}
if (hikariStats != null) {
hiConf.setMetricsTrackerFactory(hikariStats);
}
hiConf.setDataSourceProperties(dataSourceProps);
this.hikariDataSource = new HikariDataSource(hiConf);
if (flyway != null) {
flyway.setDataSource(hikariDataSource);
flyway.migrate();
}
//proxy the datasource
DataSource dataSource;
if (proxyDataSourceBuilder != null) {
proxiedDataSource = proxyDataSourceBuilder
.dataSource(hikariDataSource)
.build();
dataSource = proxiedDataSource;
} else {
proxiedDataSource = null;
dataSource = hikariDataSource;
}
//add entities provided by this lib
entityPackages.add("space.npstr.sqlsauce.entities");
// jpa
final PersistenceUnitInfo puInfo = defaultPersistenceUnitInfo(dataSource, entityPackages, dbName);
// hibernate
if (hibernateStats != null) {
hibernateProps.put("hibernate.generate_statistics", "true");
}
this.emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(puInfo, hibernateProps);
if (hibernateStats != null) {
hibernateStats.add(this.emf.unwrap(SessionFactoryImpl.class), dbName);
}
this.state = DatabaseState.READY;
if (checkConnection) {
this.connectionCheck = Executors.newSingleThreadScheduledExecutor(
runnable -> {
Thread thread = new Thread(runnable, "db-connection-check-" + dbName);
thread.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception in connection checker thread {}", t.getName(), e));
return thread;
}
);
this.connectionCheck.scheduleAtFixedRate(this::healthCheck, 5, 5, TimeUnit.SECONDS);
} else {
this.connectionCheck = null;
}
SaucedEntity.setDefaultSauce(new DatabaseWrapper(this));
} catch (final Exception e) {
this.state = DatabaseState.FAILED;
throw new DatabaseException("Failed to create database connection", e);
}
}
@CheckReturnValue
public String getName() {
return this.dbName;
}
public int getMaxPoolSize() {
return hikariDataSource.getMaximumPoolSize();
}
@CheckReturnValue
public EntityManager getEntityManager() throws IllegalStateException, DatabaseException {
if (this.state == DatabaseState.SHUTDOWN) {
throw new IllegalStateException("Database connection has been shutdown.");
} else if (this.state != DatabaseState.READY) {
throw new DatabaseException("Database connection is not available.");
}
return this.emf.createEntityManager();
}
public DataSource getDataSource() {
if (proxiedDataSource != null) {
return proxiedDataSource;
} else {
return hikariDataSource;
}
}
public void shutdown() {
if (connectionCheck != null) {
this.connectionCheck.shutdown();
try {
this.connectionCheck.awaitTermination(30, TimeUnit.SECONDS);
} catch (final InterruptedException ignored) {
}
}
this.state = DatabaseState.SHUTDOWN;
this.emf.close();
this.hikariDataSource.close();
if (this.sshTunnel != null) {
this.sshTunnel.disconnect();
}
}
/**
* @return true if the database is operational, false if not
*/
@CheckReturnValue
public boolean isAvailable() {
return this.state == DatabaseState.READY;
}
/**
* Perform a health check and try to reconnect in a blocking fashion if the health check fails
* <p>
* The healthcheck has to be called proactively, as the ssh tunnel does not provide any callback for detecting a
* disconnect. The default configuration of the database connection takes care of doing this every few seconds.
*
* The period this is called should be smaller than the tunnel force reconnect time.
*
* @return true if the database is healthy, false otherwise. Will return false if the database is shutdown, but not
* attempt to restart/reconnect it.
*/
@SuppressFBWarnings("IS")
public synchronized boolean healthCheck() {
if (this.state == DatabaseState.SHUTDOWN) {
return false;
}
//is the ssh connection still alive?
if (this.sshTunnel != null) {
boolean reconnectTunnel = false;
if (!this.sshTunnel.isConnected()) {
log.error("SSH tunnel lost connection.");
reconnectTunnel = true;
} else if (tunnelForceReconnectAfter > 0 && System.nanoTime() - lastConnected > tunnelForceReconnectAfter) {
log.error("Last successful test query older than {}ms despite connected tunnel, forcefully reconnecting the tunnel.",
tunnelForceReconnectAfter);
reconnectTunnel = true;
}
if (reconnectTunnel) {
this.state = DatabaseState.FAILED;
try {
this.sshTunnel.reconnect();
} catch (Exception e) {
log.error("Failed to reconnect tunnel during healthcheck", e);
}
}
}
boolean testQuerySuccess = false;
try {
testQuerySuccess = runTestQuery();
} catch (Exception e) {
log.error("Test query failed", e);
}
if (testQuerySuccess) {
this.state = DatabaseState.READY;
lastConnected = System.nanoTime();
return true;
} else {
this.state = DatabaseState.FAILED;
return false;
}
}
/**
* @return true if the test query was successful and false if not
*/
@CheckReturnValue
public boolean runTestQuery() {
final EntityManager em = this.emf.createEntityManager();
try {
em.getTransaction().begin();
em.createNativeQuery(TEST_QUERY).getResultList();
em.getTransaction().commit();
return true;
} catch (final PersistenceException e) {
log.error("Test query failed", e);
return false;
} finally {
em.close();
}
}
//copy pasta'd this from somewhere on stackoverflow, seems to work with slight adjustments
@CheckReturnValue
private PersistenceUnitInfo defaultPersistenceUnitInfo(final DataSource ds,
final Collection<String> entityPackages,
final String persistenceUnitName) {
return new PersistenceUnitInfo() {
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
@Override
public DataSource getJtaDataSource() {
return ds;
}
@Override
public DataSource getNonJtaDataSource() {
return ds;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@Nullable
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return entityPackages.stream()
.flatMap(entityPackage -> {
try {
return getClassesForPackage(entityPackage).stream().map(Class::getName);
} catch (DatabaseException e) {
log.error("Failed to load entity package {}", entityPackage, e);
return Stream.empty();
}
})
.collect(Collectors.toList());
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Nullable
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Nullable
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
return new Properties();
}
@Nullable
@Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
@Nullable
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public void addTransformer(final ClassTransformer transformer) {
//do nothing
}
@Nullable
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
//ugly code below this don't look please
//https://stackoverflow.com/a/3527428
// its only here to avoid the mistake of forgetting to manually add an entity class to the jpa managed classes
// why, you ask? because I want to avoid using xml files to configure the database connection (no reason really, I
// just want to know if it's possible), but at the same time I don't want to add spring or other frameworks who
// allow xml free configuration (and have methods to add whole packages to be monitored for managed classes)
@CheckReturnValue
private static List<Class<?>> getClassesForPackage(final String pkgName) throws DatabaseException {
final List<Class<?>> classes = new ArrayList<>();
// Get a File object for the package
File directory;
final String fullPath;
final String relPath = pkgName.replace('.', '/');
log.trace("ClassDiscovery: Package: " + pkgName + " becomes Path:" + relPath);
final URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
log.trace("ClassDiscovery: Resource = " + resource);
if (resource == null) {
throw new DatabaseException("No resource for " + relPath);
}
fullPath = resource.getFile();
log.trace("ClassDiscovery: FullPath = " + resource);
try {
directory = new File(resource.toURI());
} catch (final URISyntaxException e) {
throw new DatabaseException(pkgName + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e);
} catch (final IllegalArgumentException e) {
directory = null;
}
log.trace("ClassDiscovery: Directory = " + directory);
if (directory != null && directory.exists()) {
// Get the list of the files contained in the package
final String[] files = directory.list();
if (files != null) {
for (final String file : files) {
// we are only interested in .class files
if (file.endsWith(".class")) {
// removes the .class extension
final String className = pkgName + '.' + file.substring(0, file.length() - 6);
log.trace("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new DatabaseException("ClassNotFoundException loading " + className);
}
}
}
}
} else {
final String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
try (final JarFile jarFile = new JarFile(jarPath)) {
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
log.trace("ClassDiscovery: JarEntry: " + entryName);
final String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
//skip packages
if (className.endsWith(".")) {
continue;
}
//just a class
log.trace("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new DatabaseException("ClassNotFoundException loading " + className);
}
}
}
} catch (final IOException e) {
throw new DatabaseException(pkgName + " (" + directory + ") does not appear to be a valid package", e);
}
}
return classes;
}
public enum DatabaseState {
UNINITIALIZED,
INITIALIZING,
FAILED,
READY,
SHUTDOWN
}
//builder pattern, duh
public static class Builder {
public static Properties getDefaultDataSourceProps() {
final Properties dataSourceProps = new Properties();
// allow postgres to cast strings (varchars) more freely to actual column types
// source https://jdbc.postgresql.org/documentation/head/connect.html
dataSourceProps.setProperty("stringtype", "unspecified");
return dataSourceProps;
}
public static HikariConfig getDefaultHikariConfig() {
final HikariConfig hikariConfig = new HikariConfig();
//more database connections don't help with performance, so use a default value based on available cores
//http://www.dailymotion.com/video/x2s8uec_oltp-performance-concurrent-mid-tier-connections_tech
hikariConfig.setMaximumPoolSize(Math.max(Runtime.getRuntime().availableProcessors(), 4));
//timeout the validation query (will be done automatically through Connection.isValid())
hikariConfig.setValidationTimeout(3000);
hikariConfig.setConnectionTimeout(10000);
hikariConfig.setAutoCommit(false);
hikariConfig.setDriverClassName("org.postgresql.Driver");
return hikariConfig;
}
public static Properties getDefaultHibernateProps() {
final Properties hibernateProps = new Properties();
//validate entities vs existing tables
//For more info see:
// https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
//Interesting options:
//Set to "update" to have hibernate autogenerate and migrate tables for you (dangerous and requires proper
// care, probably a bad idea for serious projects in production, use flyway or something else for migrations instead)
//Set to "none" to disable completely
hibernateProps.put("hibernate.hbm2ddl.auto", "validate");
//pl0x no log spam
//NOTE: despite those logs turned off, hibernate still spams tons of debug logs, so you really want to turn
// those completely off in the slf4j implementation you are using
hibernateProps.put("hibernate.show_sql", "false");
hibernateProps.put("hibernate.session.events.log", "false");
//dont generate statistics; this will be overridden to true if a HibernateStatisticsCollector is provided
hibernateProps.put("hibernate.generate_statistics", "false");
//sane batch sizes
hibernateProps.put("hibernate.default_batch_fetch_size", 100);
hibernateProps.put("hibernate.jdbc.batch_size", 100);
//disable autocommit, it is not recommended for our use cases, and interferes with some of them
// see https://vladmihalcea.com/2017/05/17/why-you-should-always-use-hibernate-connection-provider_disables_autocommit-for-resource-local-jpa-transactions/
// this also means all EntityManager interactions need to be wrapped into em.getTransaction.begin() and
// em.getTransaction.commit() to prevent a rollback spam at the database
hibernateProps.put("hibernate.connection.autocommit", "false");
hibernateProps.put("hibernate.connection.provider_disables_autocommit", "true");
return hibernateProps;
}
private String dbName;
private String jdbcUrl;
private Properties dataSourceProps = getDefaultDataSourceProps();
private HikariConfig hikariConfig = getDefaultHikariConfig();
private Properties hibernateProps = getDefaultHibernateProps();
private Collection<String> entityPackages = new ArrayList<>();
@Nullable
private String poolName;
@Nullable
private SshTunnel.SshDetails sshDetails;
@Nullable
private HibernateStatisticsCollector hibernateStats;
@Nullable
private MetricsTrackerFactory hikariStats;
private boolean checkConnection = true;
private long tunnelForceReconnectAfter = DEFAULT_FORCE_RECONNECT_TUNNEL_AFTER;
@Nullable
private ProxyDataSourceBuilder proxyDataSourceBuilder;
@Nullable
private Flyway flyway;
// absolute minimum needed config
@CheckReturnValue
public Builder(final String dbName, final String jdbcUrl) {
this.dbName = dbName;
this.jdbcUrl = jdbcUrl;
}
/**
* Give this database connection a name - preferably unique inside your application.
*/
@CheckReturnValue
public Builder setDatabaseName(final String dbName) {
this.dbName = dbName;
return this;
}
@CheckReturnValue
public Builder setJdbcUrl(final String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
return this;
}
// datasource stuff
/**
* Set your own DataSource props. By default, the builder populates the DataSource properties with
* {@link Builder#getDefaultDataSourceProps()}, which can be overriden using this method. Use
* {@link Builder#setDataSourceProperty(Object, Object)} if you want to add a single property.
*/
@CheckReturnValue
public Builder setDataSourceProps(final Properties props) {
this.dataSourceProps = props;
return this;
}
@CheckReturnValue
public Builder setDataSourceProperty(final Object key, final Object value) {
this.dataSourceProps.put(key, value);
return this;
}
/**
* Name that the connections will show up with in db management tools
*/
@CheckReturnValue
public Builder setAppName(final String appName) {
this.dataSourceProps.setProperty("ApplicationName", appName);
return this;
}
//hikari stuff
/**
* Set your own HikariDataSource. By default, the builder populates the HikariDataSource properties with
* {@link Builder#getDefaultHikariConfig()} ()} ()}, which can be overriden using this method.
*/
@CheckReturnValue
public Builder setHikariConfig(final HikariConfig hikariConfig) {
this.hikariConfig = hikariConfig;
return this;
}
/**
* Name of the Hikari pool. Should be unique across your application. If you don't set one or set a null one
* a default pool name based on the database name will be picked.
*/
@CheckReturnValue
public Builder setPoolName(@Nullable final String poolName) {
this.poolName = poolName;
return this;
}
//hibernate stuff
/**
* Set your own Hibernate props. By default, the builder populates the Hibernate properties with
* {@link Builder#getDefaultHibernateProps()}, which can be overriden using this method. Use
* {@link Builder#setHibernateProperty(Object, Object)} if you want to add a single property.
*/
@CheckReturnValue
public Builder setHibernateProps(final Properties props) {
this.hibernateProps = props;
return this;
}
@CheckReturnValue
public Builder setHibernateProperty(final Object key, final Object value) {
this.hibernateProps.put(key, value);
return this;
}
/**
* Set the name of the dialect to be used, as sometimes auto detection is off (or you want to use a custom one)
* Example: "org.hibernate.dialect.PostgreSQL95Dialect"
*/
@CheckReturnValue
public Builder setDialect(final String dialect) {
return setHibernateProperty("hibernate.dialect", dialect);
}
@CheckReturnValue
public Builder setEntityPackages(final Collection<String> entityPackages) {
this.entityPackages = entityPackages;
return this;
}
/**
* Add all packages of your application that contain entities that you want to use with this connection.
* Example: "com.example.yourorg.yourproject.db.entities"
*/
@CheckReturnValue
public Builder addEntityPackage(final String entityPackage) {
this.entityPackages.add(entityPackage);
return this;
}
// ssh stuff
/**
* Set this to tunnel the database connection through the configured SSH tunnel. Provide a null object to reset.
*/
@CheckReturnValue
public Builder setSshDetails(@Nullable final SshTunnel.SshDetails sshDetails) {
this.sshDetails = sshDetails;
return this;
}
// metrics stuff
@CheckReturnValue
public Builder setHikariStats(@Nullable final MetricsTrackerFactory hikariStats) {
this.hikariStats = hikariStats;
return this;
}
/**
* Providing a HibernateStatisticsCollector will also enable Hibernate statistics equivalent to
* <p>
* hibernateProps.put("hibernate.generate_statistics", "true");
* <p>
* for the resulting DatabaseConnection.
*/
@CheckReturnValue
public Builder setHibernateStats(@Nullable final HibernateStatisticsCollector hibernateStats) {
this.hibernateStats = hibernateStats;
return this;
}
//migrations
@CheckReturnValue
public Builder setFlyway(@Nullable final Flyway flyway) {
this.flyway = flyway;
return this;
}
//misc
@CheckReturnValue
public Builder setCheckConnection(final boolean checkConnection) {
this.checkConnection = checkConnection;
return this;
}
/**
* Set to 0 to never force reconnect the tunnel. Other than that, the force reconnect period should be higher
* than the healthcheck period. Default is 1 minute.
*/
@CheckReturnValue
public Builder setTunnelForceReconnectAfter(final long tunnelForceReconnectAfter, TimeUnit timeUnit) {
this.tunnelForceReconnectAfter = timeUnit.toNanos(tunnelForceReconnectAfter);
return this;
}
@CheckReturnValue
public Builder setProxyDataSourceBuilder(@Nullable final ProxyDataSourceBuilder proxyBuilder) {
this.proxyDataSourceBuilder = proxyBuilder;
return this;
}
@CheckReturnValue
public DatabaseConnection build() throws DatabaseException {
return new DatabaseConnection(
this.dbName,
this.jdbcUrl,
this.dataSourceProps,
this.hikariConfig,
this.hibernateProps,
this.entityPackages,
this.poolName,
this.sshDetails,
this.hikariStats,
this.hibernateStats,
this.checkConnection,
this.tunnelForceReconnectAfter,
this.proxyDataSourceBuilder,
this.flyway
);
}
}
}
| sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseConnection.java | /*
* MIT License
*
* Copyright (c) 2017 Dennis Neufeld
*
* 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 space.npstr.sqlsauce;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.metrics.MetricsTrackerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.prometheus.client.hibernate.HibernateStatisticsCollector;
import net.ttddyy.dsproxy.support.ProxyDataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.flywaydb.core.Flyway;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.entities.SaucedEntity;
import space.npstr.sqlsauce.ssh.SshTunnel;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by napster on 29.05.17.
* <p>
* Connection to a database through an optional SSH tunnel
*/
public class DatabaseConnection {
private static final Logger log = LoggerFactory.getLogger(DatabaseConnection.class);
private static final String TEST_QUERY = "SELECT 1;";
private final EntityManagerFactory emf;
private final HikariDataSource hikariDataSource;
@Nullable
private final ProxyDataSource proxiedDataSource;
@Nullable
private SshTunnel sshTunnel = null;
private final String dbName; //a comprehensible name for this connection
private volatile DatabaseState state = DatabaseState.UNINITIALIZED;
@Nullable
private final ScheduledExecutorService connectionCheck;
/**
* @param dbName name for this database connection, also used as the persistence unit name and other
* places. Make sure it is unique across your application for best results.
* @param jdbcUrl where to find the db, which user, which pw, etc; see easy to find jdbc url docs on the web
* @param dataSourceProps properties for the underlying data source. see {@link Builder#getDefaultDataSourceProps()} for a start
* @param hikariConfig config for hikari. see {@link Builder#getDefaultHikariConfig()} ()} for a start
* @param hibernateProps properties for hibernate. see {@link Builder#getDefaultHibernateProps()} ()} for a start
* @param entityPackages example: "space.npstr.wolfia.db.entity", the names of the packages containing your
* annotated entities. root package names are fine, they will pick up all children
* @param poolName optional name for the connection pool; if null, a default name based on the db name will be picked
* @param sshDetails optionally ssh tunnel the connection; highly recommended for all remote databases
* @param hibernateStats optional metrics for hibernate. make sure to register it after adding all connections to it
* @param hikariStats optional metrics for hikari
* @param checkConnection set to false to disable a periodic healthcheck and automatic reconnection of the connection.
* only recommended if you run your own healthcheck and reconnection logic
* @param proxyDataSourceBuilder optional datasource proxy that is useful for logging and intercepting queries, see
* https://github.com/ttddyy/datasource-proxy. The hikari datasource will be set on it,
* and the resulting proxy will be passed to hibernate.
* @param flyway optional Flyway migrations. This constructor will call Flyway#setDataSource and
* Flyway#migrate() after creating the ssh tunnel and hikari datasource, and before handing
* the datasource over to the datasource proxy and hibernate. If you need tighter control
* over the handling of migrations, consider running them manually before creating the
* DatabaseConnection. Flyway supports the use of a jdbcUrl instead of a datasource, and
* you can also manually build a temporary ssh tunnel if need be.
*/
public DatabaseConnection(final String dbName,
final String jdbcUrl,
final Properties dataSourceProps,
final HikariConfig hikariConfig,
final Properties hibernateProps,
final Collection<String> entityPackages,
@Nullable final String poolName,
@Nullable final SshTunnel.SshDetails sshDetails,
@Nullable final MetricsTrackerFactory hikariStats,
@Nullable final HibernateStatisticsCollector hibernateStats,
final boolean checkConnection,
@Nullable final ProxyDataSourceBuilder proxyDataSourceBuilder,
@Nullable final Flyway flyway) throws DatabaseException {
this.dbName = dbName;
this.state = DatabaseState.INITIALIZING;
try {
// create ssh tunnel
if (sshDetails != null) {
this.sshTunnel = new SshTunnel(sshDetails).connect();
}
// hikari connection pool
final HikariConfig hiConf = new HikariConfig();
hikariConfig.copyStateTo(hiConf); //dont touch the provided config, it might get reused outside, instead use a copy
hiConf.setJdbcUrl(jdbcUrl);
if (poolName != null && !poolName.isEmpty()) {
hiConf.setPoolName(poolName);
} else {
hiConf.setPoolName(dbName + "-DefaultPool");
}
if (hikariStats != null) {
hiConf.setMetricsTrackerFactory(hikariStats);
}
hiConf.setDataSourceProperties(dataSourceProps);
this.hikariDataSource = new HikariDataSource(hiConf);
if (flyway != null) {
flyway.setDataSource(hikariDataSource);
flyway.migrate();
}
//proxy the datasource
DataSource dataSource;
if (proxyDataSourceBuilder != null) {
proxiedDataSource = proxyDataSourceBuilder
.dataSource(hikariDataSource)
.build();
dataSource = proxiedDataSource;
} else {
proxiedDataSource = null;
dataSource = hikariDataSource;
}
//add entities provided by this lib
entityPackages.add("space.npstr.sqlsauce.entities");
// jpa
final PersistenceUnitInfo puInfo = defaultPersistenceUnitInfo(dataSource, entityPackages, dbName);
// hibernate
if (hibernateStats != null) {
hibernateProps.put("hibernate.generate_statistics", "true");
}
this.emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(puInfo, hibernateProps);
if (hibernateStats != null) {
hibernateStats.add(this.emf.unwrap(SessionFactoryImpl.class), dbName);
}
this.state = DatabaseState.READY;
if (checkConnection) {
this.connectionCheck = Executors.newSingleThreadScheduledExecutor(
runnable -> {
Thread thread = new Thread(runnable, "db-connection-check-" + dbName);
thread.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception in connection checker thread {}", t.getName(), e));
return thread;
}
);
this.connectionCheck.scheduleAtFixedRate(this::healthCheck, 5, 5, TimeUnit.SECONDS);
} else {
this.connectionCheck = null;
}
SaucedEntity.setDefaultSauce(new DatabaseWrapper(this));
} catch (final Exception e) {
this.state = DatabaseState.FAILED;
throw new DatabaseException("Failed to create database connection", e);
}
}
@CheckReturnValue
public String getName() {
return this.dbName;
}
public int getMaxPoolSize() {
return hikariDataSource.getMaximumPoolSize();
}
@CheckReturnValue
public EntityManager getEntityManager() throws IllegalStateException, DatabaseException {
if (this.state == DatabaseState.SHUTDOWN) {
throw new IllegalStateException("Database connection has been shutdown.");
} else if (this.state != DatabaseState.READY) {
throw new DatabaseException("Database connection is not available.");
}
return this.emf.createEntityManager();
}
public DataSource getDataSource() {
if (proxiedDataSource != null) {
return proxiedDataSource;
} else {
return hikariDataSource;
}
}
public void shutdown() {
if (connectionCheck != null) {
this.connectionCheck.shutdown();
try {
this.connectionCheck.awaitTermination(30, TimeUnit.SECONDS);
} catch (final InterruptedException ignored) {
}
}
this.state = DatabaseState.SHUTDOWN;
this.emf.close();
this.hikariDataSource.close();
if (this.sshTunnel != null) {
this.sshTunnel.disconnect();
}
}
/**
* @return true if the database is operational, false if not
*/
@CheckReturnValue
public boolean isAvailable() {
return this.state == DatabaseState.READY;
}
/**
* Perform a health check and try to reconnect in a blocking fashion if the health check fails
* <p>
* The healthcheck has to be called proactively, as the ssh tunnel does not provide any callback for detecting a
* disconnect. The default configuration of the database connection takes care of doing this every few seconds.
*
* @return true if the database is healthy, false otherwise. Will return false if the database is shutdown, but not
* attempt to restart/reconnect it.
*/
@SuppressFBWarnings("IS")
public synchronized boolean healthCheck() {
if (this.state == DatabaseState.SHUTDOWN) {
return false;
}
//is the ssh connection still alive?
if (this.sshTunnel != null && !this.sshTunnel.isConnected()) {
log.error("SSH tunnel lost connection.");
this.state = DatabaseState.FAILED;
try {
this.sshTunnel.reconnect();
} catch (Exception e) {
log.error("Failed to reconnect tunnel during healthcheck", e);
}
}
boolean testQuerySuccess = false;
try {
testQuerySuccess = runTestQuery();
} catch (Exception e) {
log.error("Test query failed", e);
}
if (testQuerySuccess) {
this.state = DatabaseState.READY;
return true;
} else {
this.state = DatabaseState.FAILED;
return false;
}
}
/**
* @return true if the test query was successful and false if not
*/
@CheckReturnValue
public boolean runTestQuery() {
final EntityManager em = this.emf.createEntityManager();
try {
em.getTransaction().begin();
em.createNativeQuery(TEST_QUERY).getResultList();
em.getTransaction().commit();
return true;
} catch (final PersistenceException e) {
log.error("Test query failed", e);
return false;
} finally {
em.close();
}
}
//copy pasta'd this from somewhere on stackoverflow, seems to work with slight adjustments
@CheckReturnValue
private PersistenceUnitInfo defaultPersistenceUnitInfo(final DataSource ds,
final Collection<String> entityPackages,
final String persistenceUnitName) {
return new PersistenceUnitInfo() {
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
@Override
public DataSource getJtaDataSource() {
return ds;
}
@Override
public DataSource getNonJtaDataSource() {
return ds;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@Nullable
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return entityPackages.stream()
.flatMap(entityPackage -> {
try {
return getClassesForPackage(entityPackage).stream().map(Class::getName);
} catch (DatabaseException e) {
log.error("Failed to load entity package {}", entityPackage, e);
return Stream.empty();
}
})
.collect(Collectors.toList());
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Nullable
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Nullable
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
return new Properties();
}
@Nullable
@Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
@Nullable
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public void addTransformer(final ClassTransformer transformer) {
//do nothing
}
@Nullable
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
//ugly code below this don't look please
//https://stackoverflow.com/a/3527428
// its only here to avoid the mistake of forgetting to manually add an entity class to the jpa managed classes
// why, you ask? because I want to avoid using xml files to configure the database connection (no reason really, I
// just want to know if it's possible), but at the same time I don't want to add spring or other frameworks who
// allow xml free configuration (and have methods to add whole packages to be monitored for managed classes)
@CheckReturnValue
private static List<Class<?>> getClassesForPackage(final String pkgName) throws DatabaseException {
final List<Class<?>> classes = new ArrayList<>();
// Get a File object for the package
File directory;
final String fullPath;
final String relPath = pkgName.replace('.', '/');
log.trace("ClassDiscovery: Package: " + pkgName + " becomes Path:" + relPath);
final URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
log.trace("ClassDiscovery: Resource = " + resource);
if (resource == null) {
throw new DatabaseException("No resource for " + relPath);
}
fullPath = resource.getFile();
log.trace("ClassDiscovery: FullPath = " + resource);
try {
directory = new File(resource.toURI());
} catch (final URISyntaxException e) {
throw new DatabaseException(pkgName + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e);
} catch (final IllegalArgumentException e) {
directory = null;
}
log.trace("ClassDiscovery: Directory = " + directory);
if (directory != null && directory.exists()) {
// Get the list of the files contained in the package
final String[] files = directory.list();
if (files != null) {
for (final String file : files) {
// we are only interested in .class files
if (file.endsWith(".class")) {
// removes the .class extension
final String className = pkgName + '.' + file.substring(0, file.length() - 6);
log.trace("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new DatabaseException("ClassNotFoundException loading " + className);
}
}
}
}
} else {
final String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
try (final JarFile jarFile = new JarFile(jarPath)) {
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
log.trace("ClassDiscovery: JarEntry: " + entryName);
final String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
//skip packages
if (className.endsWith(".")) {
continue;
}
//just a class
log.trace("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new DatabaseException("ClassNotFoundException loading " + className);
}
}
}
} catch (final IOException e) {
throw new DatabaseException(pkgName + " (" + directory + ") does not appear to be a valid package", e);
}
}
return classes;
}
public enum DatabaseState {
UNINITIALIZED,
INITIALIZING,
FAILED,
READY,
SHUTDOWN
}
//builder pattern, duh
public static class Builder {
public static Properties getDefaultDataSourceProps() {
final Properties dataSourceProps = new Properties();
// allow postgres to cast strings (varchars) more freely to actual column types
// source https://jdbc.postgresql.org/documentation/head/connect.html
dataSourceProps.setProperty("stringtype", "unspecified");
return dataSourceProps;
}
public static HikariConfig getDefaultHikariConfig() {
final HikariConfig hikariConfig = new HikariConfig();
//more database connections don't help with performance, so use a default value based on available cores
//http://www.dailymotion.com/video/x2s8uec_oltp-performance-concurrent-mid-tier-connections_tech
hikariConfig.setMaximumPoolSize(Math.max(Runtime.getRuntime().availableProcessors(), 4));
//timeout the validation query (will be done automatically through Connection.isValid())
hikariConfig.setValidationTimeout(3000);
hikariConfig.setConnectionTimeout(10000);
hikariConfig.setAutoCommit(false);
hikariConfig.setDriverClassName("org.postgresql.Driver");
return hikariConfig;
}
public static Properties getDefaultHibernateProps() {
final Properties hibernateProps = new Properties();
//validate entities vs existing tables
//For more info see:
// https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
//Interesting options:
//Set to "update" to have hibernate autogenerate and migrate tables for you (dangerous and requires proper
// care, probably a bad idea for serious projects in production, use flyway or something else for migrations instead)
//Set to "none" to disable completely
hibernateProps.put("hibernate.hbm2ddl.auto", "validate");
//pl0x no log spam
//NOTE: despite those logs turned off, hibernate still spams tons of debug logs, so you really want to turn
// those completely off in the slf4j implementation you are using
hibernateProps.put("hibernate.show_sql", "false");
hibernateProps.put("hibernate.session.events.log", "false");
//dont generate statistics; this will be overridden to true if a HibernateStatisticsCollector is provided
hibernateProps.put("hibernate.generate_statistics", "false");
//sane batch sizes
hibernateProps.put("hibernate.default_batch_fetch_size", 100);
hibernateProps.put("hibernate.jdbc.batch_size", 100);
//disable autocommit, it is not recommended for our use cases, and interferes with some of them
// see https://vladmihalcea.com/2017/05/17/why-you-should-always-use-hibernate-connection-provider_disables_autocommit-for-resource-local-jpa-transactions/
// this also means all EntityManager interactions need to be wrapped into em.getTransaction.begin() and
// em.getTransaction.commit() to prevent a rollback spam at the database
hibernateProps.put("hibernate.connection.autocommit", "false");
hibernateProps.put("hibernate.connection.provider_disables_autocommit", "true");
return hibernateProps;
}
private String dbName;
private String jdbcUrl;
private Properties dataSourceProps = getDefaultDataSourceProps();
private HikariConfig hikariConfig = getDefaultHikariConfig();
private Properties hibernateProps = getDefaultHibernateProps();
private Collection<String> entityPackages = new ArrayList<>();
@Nullable
private String poolName;
@Nullable
private SshTunnel.SshDetails sshDetails;
@Nullable
private HibernateStatisticsCollector hibernateStats;
@Nullable
private MetricsTrackerFactory hikariStats;
private boolean checkConnection = true;
@Nullable
private ProxyDataSourceBuilder proxyDataSourceBuilder;
@Nullable
private Flyway flyway;
// absolute minimum needed config
@CheckReturnValue
public Builder(final String dbName, final String jdbcUrl) {
this.dbName = dbName;
this.jdbcUrl = jdbcUrl;
}
/**
* Give this database connection a name - preferably unique inside your application.
*/
@CheckReturnValue
public Builder setDatabaseName(final String dbName) {
this.dbName = dbName;
return this;
}
@CheckReturnValue
public Builder setJdbcUrl(final String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
return this;
}
// datasource stuff
/**
* Set your own DataSource props. By default, the builder populates the DataSource properties with
* {@link Builder#getDefaultDataSourceProps()}, which can be overriden using this method. Use
* {@link Builder#setDataSourceProperty(Object, Object)} if you want to add a single property.
*/
@CheckReturnValue
public Builder setDataSourceProps(final Properties props) {
this.dataSourceProps = props;
return this;
}
@CheckReturnValue
public Builder setDataSourceProperty(final Object key, final Object value) {
this.dataSourceProps.put(key, value);
return this;
}
/**
* Name that the connections will show up with in db management tools
*/
@CheckReturnValue
public Builder setAppName(final String appName) {
this.dataSourceProps.setProperty("ApplicationName", appName);
return this;
}
//hikari stuff
/**
* Set your own HikariDataSource. By default, the builder populates the HikariDataSource properties with
* {@link Builder#getDefaultHikariConfig()} ()} ()}, which can be overriden using this method.
*/
@CheckReturnValue
public Builder setHikariConfig(final HikariConfig hikariConfig) {
this.hikariConfig = hikariConfig;
return this;
}
/**
* Name of the Hikari pool. Should be unique across your application. If you don't set one or set a null one
* a default pool name based on the database name will be picked.
*/
@CheckReturnValue
public Builder setPoolName(@Nullable final String poolName) {
this.poolName = poolName;
return this;
}
//hibernate stuff
/**
* Set your own Hibernate props. By default, the builder populates the Hibernate properties with
* {@link Builder#getDefaultHibernateProps()}, which can be overriden using this method. Use
* {@link Builder#setHibernateProperty(Object, Object)} if you want to add a single property.
*/
@CheckReturnValue
public Builder setHibernateProps(final Properties props) {
this.hibernateProps = props;
return this;
}
@CheckReturnValue
public Builder setHibernateProperty(final Object key, final Object value) {
this.hibernateProps.put(key, value);
return this;
}
/**
* Set the name of the dialect to be used, as sometimes auto detection is off (or you want to use a custom one)
* Example: "org.hibernate.dialect.PostgreSQL95Dialect"
*/
@CheckReturnValue
public Builder setDialect(final String dialect) {
return setHibernateProperty("hibernate.dialect", dialect);
}
@CheckReturnValue
public Builder setEntityPackages(final Collection<String> entityPackages) {
this.entityPackages = entityPackages;
return this;
}
/**
* Add all packages of your application that contain entities that you want to use with this connection.
* Example: "com.example.yourorg.yourproject.db.entities"
*/
@CheckReturnValue
public Builder addEntityPackage(final String entityPackage) {
this.entityPackages.add(entityPackage);
return this;
}
// ssh stuff
/**
* Set this to tunnel the database connection through the configured SSH tunnel. Provide a null object to reset.
*/
@CheckReturnValue
public Builder setSshDetails(@Nullable final SshTunnel.SshDetails sshDetails) {
this.sshDetails = sshDetails;
return this;
}
// metrics stuff
@CheckReturnValue
public Builder setHikariStats(@Nullable final MetricsTrackerFactory hikariStats) {
this.hikariStats = hikariStats;
return this;
}
/**
* Providing a HibernateStatisticsCollector will also enable Hibernate statistics equivalent to
* <p>
* hibernateProps.put("hibernate.generate_statistics", "true");
* <p>
* for the resulting DatabaseConnection.
*/
@CheckReturnValue
public Builder setHibernateStats(@Nullable final HibernateStatisticsCollector hibernateStats) {
this.hibernateStats = hibernateStats;
return this;
}
//migrations
@CheckReturnValue
public Builder setFlyway(@Nullable final Flyway flyway) {
this.flyway = flyway;
return this;
}
//misc
@CheckReturnValue
public Builder setCheckConnection(final boolean checkConnection) {
this.checkConnection = checkConnection;
return this;
}
@CheckReturnValue
public Builder setProxyDataSourceBuilder(@Nullable final ProxyDataSourceBuilder proxyBuilder) {
this.proxyDataSourceBuilder = proxyBuilder;
return this;
}
@CheckReturnValue
public DatabaseConnection build() throws DatabaseException {
return new DatabaseConnection(
this.dbName,
this.jdbcUrl,
this.dataSourceProps,
this.hikariConfig,
this.hibernateProps,
this.entityPackages,
this.poolName,
this.sshDetails,
this.hikariStats,
this.hibernateStats,
this.checkConnection,
this.proxyDataSourceBuilder,
this.flyway
);
}
}
}
| Add tunnel force reconnect
| sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseConnection.java | Add tunnel force reconnect | <ide><path>qlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseConnection.java
<ide>
<ide> private static final Logger log = LoggerFactory.getLogger(DatabaseConnection.class);
<ide> private static final String TEST_QUERY = "SELECT 1;";
<add> private static final long DEFAULT_FORCE_RECONNECT_TUNNEL_AFTER = TimeUnit.MINUTES.toNanos(1);
<ide>
<ide> private final EntityManagerFactory emf;
<ide> private final HikariDataSource hikariDataSource;
<ide>
<ide> @Nullable
<ide> private final ScheduledExecutorService connectionCheck;
<add>
<add> private final long tunnelForceReconnectAfter;
<add> private long lastConnected;
<ide>
<ide> /**
<ide> * @param dbName name for this database connection, also used as the persistence unit name and other
<ide> * @param hikariStats optional metrics for hikari
<ide> * @param checkConnection set to false to disable a periodic healthcheck and automatic reconnection of the connection.
<ide> * only recommended if you run your own healthcheck and reconnection logic
<add> * @param tunnelForceReconnectAfter (nanos) will forcefully reconnect a connected tunnel as part of the
<add> * healthcheck, if there was no successful test query for this time period.
<ide> * @param proxyDataSourceBuilder optional datasource proxy that is useful for logging and intercepting queries, see
<ide> * https://github.com/ttddyy/datasource-proxy. The hikari datasource will be set on it,
<ide> * and the resulting proxy will be passed to hibernate.
<ide> @Nullable final MetricsTrackerFactory hikariStats,
<ide> @Nullable final HibernateStatisticsCollector hibernateStats,
<ide> final boolean checkConnection,
<add> long tunnelForceReconnectAfter,
<ide> @Nullable final ProxyDataSourceBuilder proxyDataSourceBuilder,
<ide> @Nullable final Flyway flyway) throws DatabaseException {
<ide> this.dbName = dbName;
<ide> this.state = DatabaseState.INITIALIZING;
<add> this.tunnelForceReconnectAfter = tunnelForceReconnectAfter;
<ide>
<ide> try {
<ide> // create ssh tunnel
<ide> if (sshDetails != null) {
<ide> this.sshTunnel = new SshTunnel(sshDetails).connect();
<add> lastConnected = System.nanoTime();
<ide> }
<ide>
<ide> // hikari connection pool
<ide> * The healthcheck has to be called proactively, as the ssh tunnel does not provide any callback for detecting a
<ide> * disconnect. The default configuration of the database connection takes care of doing this every few seconds.
<ide> *
<add> * The period this is called should be smaller than the tunnel force reconnect time.
<add> *
<ide> * @return true if the database is healthy, false otherwise. Will return false if the database is shutdown, but not
<ide> * attempt to restart/reconnect it.
<ide> */
<ide> }
<ide>
<ide> //is the ssh connection still alive?
<del> if (this.sshTunnel != null && !this.sshTunnel.isConnected()) {
<del> log.error("SSH tunnel lost connection.");
<del> this.state = DatabaseState.FAILED;
<del> try {
<del> this.sshTunnel.reconnect();
<del> } catch (Exception e) {
<del> log.error("Failed to reconnect tunnel during healthcheck", e);
<add> if (this.sshTunnel != null) {
<add> boolean reconnectTunnel = false;
<add>
<add> if (!this.sshTunnel.isConnected()) {
<add> log.error("SSH tunnel lost connection.");
<add> reconnectTunnel = true;
<add> } else if (tunnelForceReconnectAfter > 0 && System.nanoTime() - lastConnected > tunnelForceReconnectAfter) {
<add> log.error("Last successful test query older than {}ms despite connected tunnel, forcefully reconnecting the tunnel.",
<add> tunnelForceReconnectAfter);
<add> reconnectTunnel = true;
<add> }
<add>
<add> if (reconnectTunnel) {
<add> this.state = DatabaseState.FAILED;
<add> try {
<add> this.sshTunnel.reconnect();
<add> } catch (Exception e) {
<add> log.error("Failed to reconnect tunnel during healthcheck", e);
<add> }
<ide> }
<ide> }
<ide>
<ide>
<ide> if (testQuerySuccess) {
<ide> this.state = DatabaseState.READY;
<add> lastConnected = System.nanoTime();
<ide> return true;
<ide> } else {
<ide> this.state = DatabaseState.FAILED;
<ide> private HibernateStatisticsCollector hibernateStats;
<ide> @Nullable
<ide> private MetricsTrackerFactory hikariStats;
<del>
<ide> private boolean checkConnection = true;
<add> private long tunnelForceReconnectAfter = DEFAULT_FORCE_RECONNECT_TUNNEL_AFTER;
<ide> @Nullable
<ide> private ProxyDataSourceBuilder proxyDataSourceBuilder;
<ide> @Nullable
<ide> @CheckReturnValue
<ide> public Builder setCheckConnection(final boolean checkConnection) {
<ide> this.checkConnection = checkConnection;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set to 0 to never force reconnect the tunnel. Other than that, the force reconnect period should be higher
<add> * than the healthcheck period. Default is 1 minute.
<add> */
<add> @CheckReturnValue
<add> public Builder setTunnelForceReconnectAfter(final long tunnelForceReconnectAfter, TimeUnit timeUnit) {
<add> this.tunnelForceReconnectAfter = timeUnit.toNanos(tunnelForceReconnectAfter);
<ide> return this;
<ide> }
<ide>
<ide> this.hikariStats,
<ide> this.hibernateStats,
<ide> this.checkConnection,
<add> this.tunnelForceReconnectAfter,
<ide> this.proxyDataSourceBuilder,
<ide> this.flyway
<ide> ); |
|
Java | apache-2.0 | 75d816a3e8a401f0bb66c9e12681e91162dbdd07 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2005 Columbia University
*
* 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.columbia.gemma.loader.loaderutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A simple LineParser implementation that doesn't do anything. Subclass this and implement the "parseOneLine" method.
* <hr>
* <p>
* Copyright (c) 2004-2005 Columbia University
*
* @author pavlidis
* @version $Id$
*/
public abstract class BasicLineParser implements LineParser {
protected static final Log log = LogFactory.getLog( BasicLineParser.class );
private Collection<Object> results;
/**
* How often we tell the user what is happening.
*/
protected static final int ALERT_FREQUENCY = 10000;
public BasicLineParser() {
results = new HashSet<Object>();
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#parse(java.io.InputStream)
*/
public void parse( InputStream is ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
String line = null;
int count = 0;
while ( ( line = br.readLine() ) != null ) {
Object newItem = parseOneLine( line );
if ( newItem != null ) {
results.add( newItem );
count++;
}
if ( count % ALERT_FREQUENCY == 0 ) log.debug( "Read in " + count + " items..." );
}
log.info( "Read in " + count + " items..." );
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#parse(java.io.File)
*/
public void parse( File file ) throws IOException {
if ( !file.exists() || !file.canRead() ) {
throw new IOException( "Could not read from file " + file.getPath() );
}
FileInputStream stream = new FileInputStream( file );
parse( stream );
stream.close();
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#pasre(java.lang.String)
*/
public void parse( String filename ) throws IOException {
File infile = new File( filename );
parse( infile );
}
public Collection<Object> getResults() {
return results;
}
}
| src/impl/edu/columbia/gemma/loader/loaderutils/BasicLineParser.java | /*
* The Gemma project
*
* Copyright (c) 2005 Columbia University
*
* 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.columbia.gemma.loader.loaderutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A simple LineParser implementation that doesn't do anything. Subclass this and implement the "parseOneLine" method.
* <hr>
* <p>
* Copyright (c) 2004-2005 Columbia University
*
* @author pavlidis
* @version $Id$
*/
public abstract class BasicLineParser implements LineParser {
protected static final Log log = LogFactory.getLog( BasicLineParser.class );
private Collection<Object> results;
/**
* How often we tell the user what is happening.
*/
protected static final int ALERT_FREQUENCY = 10000;
public BasicLineParser() {
results = new HashSet<Object>();
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#parse(java.io.InputStream)
*/
public void parse( InputStream is ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
String line = null;
int count = 0;
while ( ( line = br.readLine() ) != null ) {
Object newItem = parseOneLine( line );
if ( newItem != null ) {
results.add( newItem );
count++;
}
if ( count % ALERT_FREQUENCY == 0 ) log.debug( "Read in " + count + " items..." );
}
log.info( "Read in " + count + " items..." );
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#parse(java.io.File)
*/
public void parse( File file ) throws IOException {
if ( !file.exists() || !file.canRead() ) {
throw new IOException( "Could not read from file " + file.getPath() );
}
FileInputStream stream = new FileInputStream( file );
parse( stream );
}
/*
* (non-Javadoc)
*
* @see baseCode.io.reader.LineParser#pasre(java.lang.String)
*/
public void parse( String filename ) throws IOException {
File infile = new File( filename );
parse( infile );
}
public Collection<Object> getResults() {
return results;
}
}
| close stream after parse
| src/impl/edu/columbia/gemma/loader/loaderutils/BasicLineParser.java | close stream after parse | <ide><path>rc/impl/edu/columbia/gemma/loader/loaderutils/BasicLineParser.java
<ide> }
<ide> FileInputStream stream = new FileInputStream( file );
<ide> parse( stream );
<add> stream.close();
<ide> }
<ide>
<ide> /* |
|
Java | apache-2.0 | 69fcff1a8f809133ff441157d46f1688a77c0974 | 0 | openfoodfacts/OpenFoodFacts-androidApp | package openfoodfacts.github.scrachx.openfood.models;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author herau
*/
public class NutrientLevelsTest {
private NutrientLevels nutrientLevels;
@Before
public void setUp(){
nutrientLevels = new NutrientLevels();
nutrientLevels.setFat(NutrimentLevel.LOW);
nutrientLevels.setSalt(NutrimentLevel.MODERATE);
nutrientLevels.setSaturatedFat(NutrimentLevel.HIGH);
nutrientLevels.setSugars(NutrimentLevel.MODERATE);
}
@Test
public void jsonSerialization_ok() {
JsonNode jsonNode = new ObjectMapper().valueToTree(nutrientLevels);
assertEquals(jsonNode.get("fat").asText(), NutrimentLevel.LOW.toString());
assertEquals(jsonNode.get("salt").asText(), NutrimentLevel.MODERATE.toString());
assertEquals(jsonNode.get("saturated-fat").asText(), NutrimentLevel.HIGH.toString());
assertEquals(jsonNode.get("sugars").asText(), NutrimentLevel.MODERATE.toString());
}
@Test
public void jsonDeserialization_ok() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
NutrientLevels nutrientLevelsResult = objectMapper.treeToValue(
objectMapper.createObjectNode()
.put("fat", "low")
.put("salt", "moderate")
.put("saturated-fat", "high")
.put("sugars", "moderate"), NutrientLevels.class);
assertEquals(nutrientLevels.getFat(), nutrientLevelsResult.getFat());
assertEquals(nutrientLevels.getSugars(), nutrientLevelsResult.getSugars());
assertEquals(nutrientLevels.getSaturatedFat(), nutrientLevelsResult.getSaturatedFat());
assertEquals(nutrientLevels.getSalt(), nutrientLevelsResult.getSalt());
}
} | app/src/test/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelsTest.java | package openfoodfacts.github.scrachx.openfood.models;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author herau
*/
public class NutrientLevelsTest {
private NutrientLevels nutrientLevels = new NutrientLevels();
@Before
public void setUp(){
nutrientLevels.setFat(NutrimentLevel.LOW);
nutrientLevels.setSalt(NutrimentLevel.MODERATE);
nutrientLevels.setSaturatedFat(NutrimentLevel.HIGH);
nutrientLevels.setSugars(NutrimentLevel.MODERATE);
}
@Test
public void jsonSerialization_ok() {
JsonNode jsonNode = new ObjectMapper().valueToTree(nutrientLevels);
assertEquals(jsonNode.get("fat").asText(), NutrimentLevel.LOW.toString());
assertEquals(jsonNode.get("salt").asText(), NutrimentLevel.MODERATE.toString());
assertEquals(jsonNode.get("saturated-fat").asText(), NutrimentLevel.HIGH.toString());
assertEquals(jsonNode.get("sugars").asText(), NutrimentLevel.MODERATE.toString());
}
@Test
public void jsonDeserialization_ok() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
NutrientLevels nutrientLevelsResult = objectMapper.treeToValue(
objectMapper.createObjectNode()
.put("fat", "low")
.put("salt", "moderate")
.put("saturated-fat", "high")
.put("sugars", "moderate"), NutrientLevels.class);
assertEquals(nutrientLevels.getFat(), nutrientLevelsResult.getFat());
assertEquals(nutrientLevels.getSugars(), nutrientLevelsResult.getSugars());
assertEquals(nutrientLevels.getSaturatedFat(), nutrientLevelsResult.getSaturatedFat());
assertEquals(nutrientLevels.getSalt(), nutrientLevelsResult.getSalt());
}
} | Fix for NutrientLevelTest
| app/src/test/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelsTest.java | Fix for NutrientLevelTest | <ide><path>pp/src/test/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelsTest.java
<ide> */
<ide> public class NutrientLevelsTest {
<ide>
<del> private NutrientLevels nutrientLevels = new NutrientLevels();
<add> private NutrientLevels nutrientLevels;
<ide>
<ide> @Before
<ide> public void setUp(){
<add> nutrientLevels = new NutrientLevels();
<ide> nutrientLevels.setFat(NutrimentLevel.LOW);
<ide> nutrientLevels.setSalt(NutrimentLevel.MODERATE);
<ide> nutrientLevels.setSaturatedFat(NutrimentLevel.HIGH); |
|
Java | apache-2.0 | 670a28b3439d75e90810d54236a1fe10dc2afac8 | 0 | yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1,yncxcw/PreemptYARN-2.7.1 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.PriorityQueue;
import java.util.Set;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.hash.Hash;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingEditPolicy;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
import org.apache.hadoop.yarn.util.Clock;
import org.apache.hadoop.yarn.util.SystemClock;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import com.google.common.annotations.VisibleForTesting;
/**
* This class implement a {@link SchedulingEditPolicy} that is designed to be
* paired with the {@code CapacityScheduler}. At every invocation of {@code
* editSchedule()} it computes the ideal amount of resources assigned to each
* queue (for each queue in the hierarchy), and determines whether preemption
* is needed. Overcapacity is distributed among queues in a weighted fair manner,
* where the weight is the amount of guaranteed capacity for the queue.
* Based on this ideal assignment it determines whether preemption is required
* and select a set of containers from each application that would be killed if
* the corresponding amount of resources is not freed up by the application.
*
* If not in {@code observeOnly} mode, it triggers preemption requests via a
* {@link ContainerPreemptEvent} that the {@code ResourceManager} will ensure
* to deliver to the application (or to execute).
*
* If the deficit of resources is persistent over a long enough period of time
* this policy will trigger forced termination of containers (again by generating
* {@link ContainerPreemptEvent}).
*/
public class ProportionalCapacityPreemptionPolicy implements SchedulingEditPolicy {
private static final Log LOG =
LogFactory.getLog(ProportionalCapacityPreemptionPolicy.class);
/** If true, run the policy but do not affect the cluster with preemption and
* kill events. */
public static final String OBSERVE_ONLY =
"yarn.resourcemanager.monitor.capacity.preemption.observe_only";
/** Time in milliseconds between invocations of this policy */
public static final String MONITORING_INTERVAL =
"yarn.resourcemanager.monitor.capacity.preemption.monitoring_interval";
/** Time in milliseconds between requesting a preemption from an application
* and killing the container. */
public static final String WAIT_TIME_BEFORE_KILL =
"yarn.resourcemanager.monitor.capacity.preemption.max_wait_before_kill";
/** Maximum percentage of resources preempted in a single round. By
* controlling this value one can throttle the pace at which containers are
* reclaimed from the cluster. After computing the total desired preemption,
* the policy scales it back within this limit. */
public static final String TOTAL_PREEMPTION_PER_ROUND =
"yarn.resourcemanager.monitor.capacity.preemp .tion.total_preemption_per_round";
/** Maximum amount of resources above the target capacity ignored for
* preemption. This defines a deadzone around the target capacity that helps
* prevent thrashing and oscillations around the computed target balance.
* High values would slow the time to capacity and (absent natural
* completions) it might prevent convergence to guaranteed capacity. */
public static final String MAX_IGNORED_OVER_CAPACITY =
"yarn.resourcemanager.monitor.capacity.preemption.max_ignored_over_capacity";
/**
* Given a computed preemption target, account for containers naturally
* expiring and preempt only this percentage of the delta. This determines
* the rate of geometric convergence into the deadzone ({@link
* #MAX_IGNORED_OVER_CAPACITY}). For example, a termination factor of 0.5
* will reclaim almost 95% of resources within 5 * {@link
* #WAIT_TIME_BEFORE_KILL}, even absent natural termination. */
public static final String NATURAL_TERMINATION_FACTOR =
"yarn.resourcemanager.monitor.capacity.preemption.natural_termination_factor";
public static final int PR_NUMBER = 2;
// the dispatcher to send preempt and kill events
public EventHandler<ContainerPreemptEvent> dispatcher;
private final Clock clock;
private double maxIgnoredOverCapacity;
private long maxWaitTime;
private CapacityScheduler scheduler;
private long monitoringInterval;
private final Map<RMContainer,Long> preempted =
new HashMap<RMContainer,Long>();
private ResourceCalculator rc;
private float percentageClusterPreemptionAllowed;
private double naturalTerminationFactor;
private boolean observeOnly;
private Map<NodeId, Set<String>> labels;
private boolean isSuspended = true;
public ProportionalCapacityPreemptionPolicy() {
clock = new SystemClock();
}
public ProportionalCapacityPreemptionPolicy(Configuration config,
EventHandler<ContainerPreemptEvent> dispatcher,
CapacityScheduler scheduler) {
this(config, dispatcher, scheduler, new SystemClock());
}
public ProportionalCapacityPreemptionPolicy(Configuration config,
EventHandler<ContainerPreemptEvent> dispatcher,
CapacityScheduler scheduler, Clock clock) {
init(config, dispatcher, scheduler);
this.clock = clock;
}
public void init(Configuration config,
EventHandler<ContainerPreemptEvent> disp,
PreemptableResourceScheduler sched) {
LOG.info("Preemption monitor:" + this.getClass().getCanonicalName());
assert null == scheduler : "Unexpected duplicate call to init";
if (!(sched instanceof CapacityScheduler)) {
throw new YarnRuntimeException("Class " +
sched.getClass().getCanonicalName() + " not instance of " +
CapacityScheduler.class.getCanonicalName());
}
dispatcher = disp;
scheduler = (CapacityScheduler) sched;
maxIgnoredOverCapacity = config.getDouble(MAX_IGNORED_OVER_CAPACITY, 0.1);
naturalTerminationFactor =
config.getDouble(NATURAL_TERMINATION_FACTOR, 0.2);
maxWaitTime = config.getLong(WAIT_TIME_BEFORE_KILL, 15000);
monitoringInterval = config.getLong(MONITORING_INTERVAL, 3000);
percentageClusterPreemptionAllowed =
config.getFloat(TOTAL_PREEMPTION_PER_ROUND, (float) 0.1);
observeOnly = config.getBoolean(OBSERVE_ONLY, false);
rc = scheduler.getResourceCalculator();
labels = null;
}
@VisibleForTesting
public ResourceCalculator getResourceCalculator() {
return rc;
}
@Override
public void editSchedule() {
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
clusterResources = getNonLabeledResources(clusterResources);
setNodeLabels(scheduler.getRMContext().getNodeLabelManager()
.getNodeLabels());
containerBasedPreemptOrKill(root, clusterResources);
}
/**
* Setting Node Labels
*
* @param nodelabels
*/
public void setNodeLabels(Map<NodeId, Set<String>> nodelabels) {
labels = nodelabels;
}
/**
* This method returns all non labeled resources.
*
* @param clusterResources
* @return Resources
*/
private Resource getNonLabeledResources(Resource clusterResources) {
RMContext rmcontext = scheduler.getRMContext();
RMNodeLabelsManager lm = rmcontext.getNodeLabelManager();
Resource res = lm.getResourceByLabel(RMNodeLabelsManager.NO_LABEL,
clusterResources);
return res == null ? clusterResources : res;
}
/**
* This method selects and tracks containers to be preempted. If a container
* is in the target list for more than maxWaitTime it is killed.
*
* @param root the root of the CapacityScheduler queue hierarchy
* @param clusterResources the total amount of resources in the cluster
*/
private void containerBasedPreemptOrKill(CSQueue root,
Resource clusterResources) {
// extract a summary of the queues from scheduler
TempQueue tRoot;
synchronized (scheduler) {
tRoot = cloneQueues(root, clusterResources);
}
// compute the ideal distribution of resources among queues
// updates cloned queues state accordingly
tRoot.idealAssigned = tRoot.guaranteed;
Resource totalPreemptionAllowed = Resources.multiply(clusterResources,
percentageClusterPreemptionAllowed);
List<TempQueue> queues =
recursivelyComputeIdealAssignment(tRoot, totalPreemptionAllowed);
// based on ideal allocation select containers to be preempted from each
// queue and each application
Map<ApplicationAttemptId,Map<RMContainer,Resource>> toPreempt =
getContainersToPreempt(queues, clusterResources);
if (LOG.isDebugEnabled())
{
logToCSV(queues);
}
// if we are in observeOnly mode return before any action is taken
if (observeOnly) {
return;
}
// preempt (or kill) the selected containers
for (Map.Entry<ApplicationAttemptId,Map<RMContainer,Resource>> e
: toPreempt.entrySet()) {
for (Map.Entry<RMContainer,Resource> cr : e.getValue().entrySet()) {
// if we tried to preempt this for more than maxWaitTime
RMContainer container = cr.getKey();
Resource resource = cr.getValue();
if (preempted.get(container) != null &&
preempted.get(container) + maxWaitTime < clock.getTime()) {
// suspend it
LOG.info("get container "+container.getContainerId()+" to suspend resource is "
+resource);
if(this.isSuspended){
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.SUSPEND_CONTAINER,resource));
}else{
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.KILL_CONTAINER,container.getContainer().getResource()));
}
preempted.remove(container);
} else {
//otherwise just send preemption events
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.PREEMPT_CONTAINER,resource));
if (preempted.get(container) == null) {
preempted.put(container, clock.getTime());
}
}
}
}
// Keep the preempted list clean
for (Iterator<RMContainer> i = preempted.keySet().iterator(); i.hasNext();){
RMContainer id = i.next();
// garbage collect containers that are irrelevant for preemption
if (preempted.get(id) + 2 * maxWaitTime < clock.getTime()) {
i.remove();
}
}
}
/**
* This method recursively computes the ideal assignment of resources to each
* level of the hierarchy. This ensures that leafs that are over-capacity but
* with parents within capacity will not be preempted. Preemptions are allowed
* within each subtree according to local over/under capacity.only return leaf nodes for this function
* 把所有的子queue全放在一个List里面,这里并不去区分层级关系
* @param root the root of the cloned queue hierachy
* @param totalPreemptionAllowed maximum amount of preemption allowed
* @return a list of leaf queues updated with preemption targets
*/
private List<TempQueue> recursivelyComputeIdealAssignment(
TempQueue root, Resource totalPreemptionAllowed) {
List<TempQueue> leafs = new ArrayList<TempQueue>();
if (root.getChildren() != null &&
root.getChildren().size() > 0) {
// compute ideal distribution at this level
computeIdealResourceDistribution(rc, root.getChildren(),
totalPreemptionAllowed, root.idealAssigned);
// compute recursively for lower levels and build list of leafs
for(TempQueue t : root.getChildren()) {
leafs.addAll(recursivelyComputeIdealAssignment(t, totalPreemptionAllowed));
}
} else {
// we are in a leaf nothing to do, just return yourself
return Collections.singletonList(root);
}
return leafs;
}
/**
* This method computes (for a single level in the tree, passed as a {@code
* List<TempQueue>}) the ideal assignment of resources. This is done
* recursively to allocate capacity fairly across all queues with pending
* demands. It terminates when no resources are left to assign, or when all
* demand is satisfied.
*
* @param rc resource calculator
* @param queues a list of cloned queues to be assigned capacity to (this is
* an out param)
* @param totalPreemptionAllowed total amount of preemption we allow
* @param tot_guarant the amount of capacity assigned to this pool of queues
*/
private void computeIdealResourceDistribution(ResourceCalculator rc,
List<TempQueue> queues, Resource totalPreemptionAllowed, Resource tot_guarant) {
// qAlloc tracks currently active queues (will decrease progressively as
// demand is met)
List<TempQueue> qAlloc = new ArrayList<TempQueue>(queues);
// unassigned tracks how much resources are still to assign, initialized
// with the total capacity for this set of queues
Resource unassigned = Resources.clone(tot_guarant);
// group queues based on whether they have non-zero guaranteed capacity
Set<TempQueue> nonZeroGuarQueues = new HashSet<TempQueue>();
Set<TempQueue> zeroGuarQueues = new HashSet<TempQueue>();
for (TempQueue q : qAlloc) {
if (Resources
.greaterThan(rc, tot_guarant, q.guaranteed, Resources.none())) {
nonZeroGuarQueues.add(q);
} else {
zeroGuarQueues.add(q);
}
}
// first compute the allocation as a fixpoint based on guaranteed capacity
computeFixpointAllocation(rc, tot_guarant, nonZeroGuarQueues, unassigned,
false);
// if any capacity is left unassigned, distributed among zero-guarantee
// queues uniformly (i.e., not based on guaranteed capacity, as this is zero)
if (!zeroGuarQueues.isEmpty()
&& Resources.greaterThan(rc, tot_guarant, unassigned, Resources.none())) {
computeFixpointAllocation(rc, tot_guarant, zeroGuarQueues, unassigned,
true);
}
// based on ideal assignment computed above and current assignment we derive
// how much preemption is required overall,this is resource that are preemptable
Resource totPreemptionNeeded = Resource.newInstance(0, 0);
for (TempQueue t:queues) {
if (Resources.greaterThan(rc, tot_guarant, t.current, t.idealAssigned)) {
Resources.addTo(totPreemptionNeeded,
Resources.subtract(t.current, t.idealAssigned));
}
}
// if we need to preempt more than is allowed, compute a factor (0<f<1)
// that is used to scale down how much we ask back from each queue
float scalingFactor = 1.0F;
if (Resources.greaterThan(rc, tot_guarant,
totPreemptionNeeded, totalPreemptionAllowed)) {
scalingFactor = Resources.divide(rc, tot_guarant,
totalPreemptionAllowed, totPreemptionNeeded);
}
// assign to each queue the amount of actual preemption based on local
// information of ideal preemption and scaling factor
for (TempQueue t : queues) {
t.assignPreemption(scalingFactor, rc, tot_guarant);
}
if (LOG.isDebugEnabled()) {
long time = clock.getTime();
for (TempQueue t : queues) {
LOG.debug(time + ": " + t);
}
}
}
/**
* Given a set of queues compute the fix-point distribution of unassigned
* resources among them. As pending request of a queue are exhausted, the
* queue is removed from the set and remaining capacity redistributed among
* remaining queues. The distribution is weighted based on guaranteed
* capacity, unless asked to ignoreGuarantee, in which case resources are
* distributed uniformly.
*/
private void computeFixpointAllocation(ResourceCalculator rc,
Resource tot_guarant, Collection<TempQueue> qAlloc, Resource unassigned,
boolean ignoreGuarantee) {
// Prior to assigning the unused resources, process each queue as follows:
// If current > guaranteed, idealAssigned = guaranteed + untouchable extra
// Else idealAssigned = current;
// Subtract idealAssigned resources from unassigned.
// If the queue has all of its needs met (that is, if
// idealAssigned >= current + pending), remove it from consideration.
// Sort queues from most under-guaranteed to most over-guaranteed.
TQComparator tqComparator = new TQComparator(rc, tot_guarant);
PriorityQueue<TempQueue> orderedByNeed =
new PriorityQueue<TempQueue>(10,tqComparator);
for (Iterator<TempQueue> i = qAlloc.iterator(); i.hasNext();) {
TempQueue q = i.next();
if (Resources.greaterThan(rc, tot_guarant, q.current, q.guaranteed)) {
q.idealAssigned = Resources.add(q.guaranteed, q.untouchableExtra);
} else {
q.idealAssigned = Resources.clone(q.current);
}
Resources.subtractFrom(unassigned, q.idealAssigned);
// If idealAssigned < (current + pending), q needs more resources, so
// add it to the list of underserved queues, ordered by need.
Resource curPlusPend = Resources.add(q.current, q.pending);
if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) {
orderedByNeed.add(q);
}
}
//assign all cluster resources until no more demand, or no resources are left
while (!orderedByNeed.isEmpty()
&& Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) {
Resource wQassigned = Resource.newInstance(0, 0);
// we compute normalizedGuarantees capacity based on currently active
// queues
resetCapacity(rc, unassigned, orderedByNeed, ignoreGuarantee);
// For each underserved queue (or set of queues if multiple are equally
// underserved), offer its share of the unassigned resources based on its
// normalized guarantee. After the offer, if the queue is not satisfied,
// place it back in the ordered list of queues, recalculating its place
// in the order of most under-guaranteed to most over-guaranteed. In this
// way, the most underserved queue(s) are always given resources first.
Collection<TempQueue> underserved =
getMostUnderservedQueues(orderedByNeed, tqComparator);
for (Iterator<TempQueue> i = underserved.iterator(); i.hasNext();) {
TempQueue sub = i.next();
//the share of this queue based on unassigned resource
Resource wQavail = Resources.multiplyAndNormalizeUp(rc,
unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1));
Resource wQidle = sub.offer(wQavail, rc, tot_guarant);
Resource wQdone = Resources.subtract(wQavail, wQidle);
//wQdone is 0 说明 说明wQavail已经被分配完
if (Resources.greaterThan(rc, tot_guarant,
wQdone, Resources.none())) {
// The queue is still asking for more. Put it back in the priority
// queue, recalculating its order based on need.
orderedByNeed.add(sub);
}
Resources.addTo(wQassigned, wQdone);
}
LOG.info("computeFixpointAllocation inloop unused resource: "+unassigned);
Resources.subtractFrom(unassigned, wQassigned);
}
}
// Take the most underserved TempQueue (the one on the head). Collect and
// return the list of all queues that have the same idealAssigned
// percentage of guaranteed. the less this value, the more underserved this queue
protected Collection<TempQueue> getMostUnderservedQueues(
PriorityQueue<TempQueue> orderedByNeed, TQComparator tqComparator) {
ArrayList<TempQueue> underserved = new ArrayList<TempQueue>();
while (!orderedByNeed.isEmpty()) {
TempQueue q1 = orderedByNeed.remove();
underserved.add(q1);
TempQueue q2 = orderedByNeed.peek();
// q1's pct of guaranteed won't be larger than q2's. If it's less, then
// return what has already been collected. Otherwise, q1's pct of
// guaranteed == that of q2, so add q2 to underserved list during the
// next pass.
if (q2 == null || tqComparator.compare(q1,q2) < 0) {
return underserved;
}
}
return underserved;
}
/**
* Computes a normalizedGuaranteed capacity based on active queues
* @param rc resource calculator
* @param clusterResource the total amount of resources in the cluster
* @param queues the list of queues to consider
*/
private void resetCapacity(ResourceCalculator rc, Resource clusterResource,
Collection<TempQueue> queues, boolean ignoreGuar) {
Resource activeCap = Resource.newInstance(0, 0);
if (ignoreGuar) {
for (TempQueue q : queues) {
q.normalizedGuarantee = (float) 1.0f / ((float) queues.size());
}
} else {
for (TempQueue q : queues) {
Resources.addTo(activeCap, q.guaranteed);
}
for (TempQueue q : queues) {
q.normalizedGuarantee = Resources.divide(rc, clusterResource, q.guaranteed, activeCap);
}
}
}
/**
* Based a resource preemption target drop reservations of containers and
* if necessary select containers for preemption from applications in each
* over-capacity queue. It uses {@link #NATURAL_TERMINATION_FACTOR} to
* account for containers that will naturally complete.
*
* @param queues set of leaf queues to preempt from
* @param clusterResource total amount of cluster resources
* @return a map of applciationID to set of containers to preempt
*/
private Map<ApplicationAttemptId,Map<RMContainer,Resource>> getContainersToPreempt(
List<TempQueue> queues, Resource clusterResource) {
Map<ApplicationAttemptId, Map<RMContainer,Resource>> preemptMap =
new HashMap<ApplicationAttemptId, Map<RMContainer,Resource>>();
List<RMContainer> skippedAMContainerlist = new ArrayList<RMContainer>();
for (TempQueue qT : queues) {
if (qT.preemptionDisabled && qT.leafQueue != null) {
if (LOG.isDebugEnabled()) {
if (Resources.greaterThan(rc, clusterResource,
qT.toBePreempted, Resource.newInstance(0, 0))) {
LOG.info("Tried to preempt the following "
+ "resources from non-preemptable queue: "
+ qT.queueName + " - Resources: " + qT.toBePreempted);
}
}
continue;
}
// we act only if we are violating balance by more than
// maxIgnoredOverCapacity
if (Resources.greaterThan(rc, clusterResource, qT.current,
Resources.multiply(qT.guaranteed, 1.0 + maxIgnoredOverCapacity))) {
// we introduce a dampening factor naturalTerminationFactor that
// accounts for natural termination of containers
Resource resToObtain =
Resources.multiply(qT.toBePreempted, naturalTerminationFactor);
Resource skippedAMSize = Resource.newInstance(0, 0);
// lock the leafqueue while we scan applications and unreserve
synchronized (qT.leafQueue) {
//what is the descending order
NavigableSet<FiCaSchedulerApp> ns =
(NavigableSet<FiCaSchedulerApp>) qT.leafQueue.getApplications();
Iterator<FiCaSchedulerApp> desc = ns.descendingIterator();
qT.actuallyPreempted = Resources.clone(resToObtain);
while (desc.hasNext()) {
FiCaSchedulerApp fc = desc.next();
if (Resources.lessThanOrEqual(rc, clusterResource, resToObtain,
Resources.none())) {
break;
}
LOG.info("now try to preempt applicatin:"+fc.getApplicationId());
preemptMap.put(
fc.getApplicationAttemptId(),
preemptFrom(fc, clusterResource, resToObtain,
skippedAMContainerlist, skippedAMSize));
}
//we allow preempt AM for kill based approach
if(!isSuspended){
//we will never preempt am resource
Resource maxAMCapacityForThisQueue = Resources.multiply(
Resources.multiply(clusterResource,
qT.leafQueue.getAbsoluteCapacity()),
qT.leafQueue.getMaxAMResourcePerQueuePercent());
//Can try preempting AMContainers (still saving atmost
// maxAMCapacityForThisQueue AMResource's) if more resources are
// required to be preempted from this Queue.
preemptAMContainers(clusterResource, preemptMap,
skippedAMContainerlist, resToObtain, skippedAMSize,
maxAMCapacityForThisQueue);
}
}
}
}
return preemptMap;
}
/**
* As more resources are needed for preemption, saved AMContainers has to be
* rescanned. Such AMContainers can be preempted based on resToObtain, but
* maxAMCapacityForThisQueue resources will be still retained.
*
* @param clusterResource
* @param preemptMap
* @param skippedAMContainerlist
* @param resToObtain
* @param skippedAMSize
* @param maxAMCapacityForThisQueue
*/
private void preemptAMContainers(Resource clusterResource,
Map<ApplicationAttemptId, Map<RMContainer,Resource>> preemptMap,
List<RMContainer> skippedAMContainerlist, Resource resToObtain,
Resource skippedAMSize, Resource maxAMCapacityForThisQueue) {
for (RMContainer c : skippedAMContainerlist) {
// Got required amount of resources for preemption, can stop now
if (Resources.lessThanOrEqual(rc, clusterResource, resToObtain,
Resources.none())) {
break;
}
// Once skippedAMSize reaches down to maxAMCapacityForThisQueue,
// container selection iteration for preemption will be stopped.
if (Resources.lessThanOrEqual(rc, clusterResource, skippedAMSize,
maxAMCapacityForThisQueue)) {
break;
}
Map<RMContainer,Resource> contToPrempt = preemptMap.get(c
.getApplicationAttemptId());
if (null == contToPrempt) {
contToPrempt = new HashMap<RMContainer,Resource>();
preemptMap.put(c.getApplicationAttemptId(), contToPrempt);
}
contToPrempt.put(c,c.getContainer().getResource());
Resources.subtractFrom(resToObtain, c.getContainer().getResource());
Resources.subtractFrom(skippedAMSize, c.getContainer()
.getResource());
}
skippedAMContainerlist.clear();
}
/**
* Given a target preemption for a specific application, select containers
* to preempt (after unreserving all reservation for that app).
*
* @param app
* @param clusterResource
* @param rsrcPreempt
* @return Map<RMContainer,Resource> mapping from container to resource
*/
private Map<RMContainer,Resource> preemptFrom(FiCaSchedulerApp app,
Resource clusterResource, Resource rsrcPreempt,
List<RMContainer> skippedAMContainerlist, Resource skippedAMSize) {
Map<RMContainer,Resource> ret = new HashMap<RMContainer,Resource>();
ApplicationAttemptId appId = app.getApplicationAttemptId();
// first drop reserved containers towards rsrcPreempt
List<RMContainer> reservations =
new ArrayList<RMContainer>(app.getReservedContainers());
for (RMContainer c : reservations) {
if (Resources.lessThanOrEqual(rc, clusterResource,
rsrcPreempt, Resources.none())) {
return ret;
}
if (!observeOnly) {
dispatcher.handle(new ContainerPreemptEvent(appId, c,
ContainerPreemptEventType.DROP_RESERVATION, c.getContainer().getResource()));
}
Resources.subtractFrom(rsrcPreempt, c.getContainer().getResource());
}
// if more resources are to be freed go through all live containers in
// reverse priority and reverse allocation order and mark them for
// preemption
List<RMContainer> containers =
new ArrayList<RMContainer>(((FiCaSchedulerApp)app).getUnPreemtedContainers());
sortContainers(containers);
for (RMContainer c : containers) {
if (Resources.lessThanOrEqual(rc, clusterResource,
rsrcPreempt, Resources.none())) {
return ret;
}
// Skip AM Container from preemption for now.
if (c.isAMContainer()) {
skippedAMContainerlist.add(c);
Resources.addTo(skippedAMSize, c.getContainer().getResource());
continue;
}
// skip Labeled resource
if(isLabeledContainer(c)){
continue;
}
Resource preempteThisTime;
if(isSuspended){
//compute preempted resource this round
preempteThisTime = Resources.mins(rc, clusterResource,
rsrcPreempt, c.getSRResourceUnit());
}else{
preempteThisTime = c.getContainer().getResource();
}
LOG.info("get preempted Resource: "+preempteThisTime);
ret.put(c,preempteThisTime);
//substract preempted resource
Resources.subtractFrom(rsrcPreempt, preempteThisTime);
}
return ret;
}
/**
* Checking if given container is a labeled container
*
* @param c
* @return true/false
*/
private boolean isLabeledContainer(RMContainer c) {
return labels.containsKey(c.getAllocatedNode());
}
/**
* Compare by reversed priority order first, and then reversed containerId
* order
* @param containers
*/
@VisibleForTesting
static void sortContainers(List<RMContainer> containers){
Collections.sort(containers, new Comparator<RMContainer>() {
@Override
public int compare(RMContainer a, RMContainer b) {
Comparator<Priority> c = new org.apache.hadoop.yarn.server
.resourcemanager.resource.Priority.Comparator();
int priorityComp = c.compare(b.getContainer().getPriority(),
a.getContainer().getPriority());
if (priorityComp != 0) {
return priorityComp;
}
return b.getContainerId().compareTo(a.getContainerId());
}
});
}
@Override
public long getMonitoringInterval() {
return monitoringInterval;
}
@Override
public String getPolicyName() {
return "ProportionalCapacityPreemptionPolicy";
}
/**
* This method walks a tree of CSQueue and clones the portion of the state
* relevant for preemption in TempQueue(s). It also maintains a pointer to
* the leaves. Finally it aggregates pending resources in each queue and rolls
* it up to higher levels.
*
* @param root the root of the CapacityScheduler queue hierarchy
* @param clusterResources the total amount of resources in the cluster
* @return the root of the cloned queue hierarchy
*/
private TempQueue cloneQueues(CSQueue root, Resource clusterResources) {
TempQueue ret;
synchronized (root) {
LOG.info("cloneQueues enter");
String queueName = root.getQueueName();
float absUsed = root.getAbsoluteUsedCapacity();
float absCap = root.getAbsoluteCapacity();
float absMaxCap = root.getAbsoluteMaximumCapacity();
boolean preemptionDisabled = root.getPreemptionDisabled();
Resource current;
//differenciate the resource based on if it is suspended
if(isSuspended){
current = root.getUsedResources();
}else{
current = Resources.multiply(clusterResources, absUsed);
}
Resource guaranteed = Resources.multiply(clusterResources, absCap);
Resource maxCapacity = Resources.multiply(clusterResources, absMaxCap);
LOG.info("cloneQueues current queue: "+queueName+" usedResource: "+root.getUsedResources());
LOG.info("cloneQueues current queue: "+queueName+" ratiodResource: "+Resources.multiply(clusterResources, absUsed));
Resource extra = Resource.newInstance(0, 0);
if (Resources.greaterThan(rc, clusterResources, current, guaranteed)) {
extra = Resources.subtract(current, guaranteed);
}
if (root instanceof LeafQueue) {
LeafQueue l = (LeafQueue) root;
Resource pending = l.getTotalResourcePending();
ret = new TempQueue(queueName, current, pending, guaranteed,
maxCapacity, preemptionDisabled);
if (preemptionDisabled) {
ret.untouchableExtra = extra;
} else {
ret.preemptableExtra = extra;
}
ret.setLeafQueue(l);
} else {
Resource pending = Resource.newInstance(0, 0);
ret = new TempQueue(root.getQueueName(), current, pending, guaranteed,
maxCapacity, false);
Resource childrensPreemptable = Resource.newInstance(0, 0);
for (CSQueue c : root.getChildQueues()) {
TempQueue subq = cloneQueues(c, clusterResources);
Resources.addTo(childrensPreemptable, subq.preemptableExtra);
ret.addChild(subq);
}
// untouchableExtra = max(extra - childrenPreemptable, 0)
if (Resources.greaterThanOrEqual(
rc, clusterResources, childrensPreemptable, extra)) {
//it means there are some extra resource in child node are marked untouchable.
ret.untouchableExtra = Resource.newInstance(0, 0);
} else {
ret.untouchableExtra =
Resources.subtractFrom(extra, childrensPreemptable);
}
}
}
return ret;
}
// simple printout function that reports internal queue state (useful for
// plotting)
private void logToCSV(List<TempQueue> unorderedqueues){
List<TempQueue> queues = new ArrayList<TempQueue>(unorderedqueues);
Collections.sort(queues, new Comparator<TempQueue>(){
@Override
public int compare(TempQueue o1, TempQueue o2) {
return o1.queueName.compareTo(o2.queueName);
}});
String queueState = " QUEUESTATE: " + clock.getTime();
StringBuilder sb = new StringBuilder();
sb.append(queueState);
for (TempQueue tq : queues) {
sb.append(", ");
tq.appendLogString(sb);
}
LOG.info(sb.toString());
}
/**
* Temporary data-structure tracking resource availability, pending resource
* need, current utilization. Used to clone {@link CSQueue}.
*/
static class TempQueue {
final String queueName;
final Resource current;
final Resource pending;
final Resource guaranteed;
final Resource maxCapacity;
Resource idealAssigned;
Resource toBePreempted;
Resource actuallyPreempted;
Resource untouchableExtra;
Resource preemptableExtra;
double normalizedGuarantee;
final ArrayList<TempQueue> children;
LeafQueue leafQueue;
boolean preemptionDisabled;
TempQueue(String queueName, Resource current, Resource pending,
Resource guaranteed, Resource maxCapacity, boolean preemptionDisabled) {
this.queueName = queueName;
this.current = current;
this.pending = pending;
this.guaranteed = guaranteed;
this.maxCapacity = maxCapacity;
this.idealAssigned = Resource.newInstance(0, 0);
this.actuallyPreempted = Resource.newInstance(0, 0);
this.toBePreempted = Resource.newInstance(0, 0);
this.normalizedGuarantee = Float.NaN;
this.children = new ArrayList<TempQueue>();
//both leaf and parent node may have untouchable resource
this.untouchableExtra = Resource.newInstance(0, 0);
//only leaf node has preemptable extra
this.preemptableExtra = Resource.newInstance(0, 0);
this.preemptionDisabled = preemptionDisabled;
}
public void setLeafQueue(LeafQueue l){
assert children.size() == 0;
this.leafQueue = l;
}
/**
* When adding a child we also aggregate its pending resource needs.
* @param q the child queue to add to this queue
*/
public void addChild(TempQueue q) {
assert leafQueue == null;
children.add(q);
Resources.addTo(pending, q.pending);
}
public void addChildren(ArrayList<TempQueue> queues) {
assert leafQueue == null;
children.addAll(queues);
}
public ArrayList<TempQueue> getChildren(){
return children;
}
// This function "accepts" all the resources it can (pending) and return
// the unused ones
Resource offer(Resource avail, ResourceCalculator rc,
Resource clusterResource) {
Resource absMaxCapIdealAssignedDelta = Resources.componentwiseMax(
Resources.subtract(maxCapacity, idealAssigned),
Resource.newInstance(0, 0));
// remain = avail - min(avail, (max - assigned), (current + pending - assigned))
// we have bug here. in some case:
//(current + pending - assigned).core > avail.core
//(current + pending - assigned).memo < avail.memo
//so we get least cores of the three and least memory of the three
Resource accepted =
Resources.mins(rc, clusterResource,
absMaxCapIdealAssignedDelta,
Resources.mins(rc, clusterResource, avail, Resources.subtract(
Resources.add(current, pending), idealAssigned)));
Resource remain = Resources.subtract(avail, accepted);
Resources.addTo(idealAssigned, accepted);
LOG.info("queueName: "+queueName);
LOG.info("avaul: "+avail);
LOG.info("absMaxDelta: "+absMaxCapIdealAssignedDelta);
LOG.info("max: "+maxCapacity);
LOG.info("current: "+current);
LOG.info("pending: "+pending);
LOG.info("acceped: "+accepted);
LOG.info("ideal: "+idealAssigned);
return remain;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" NAME: " + queueName)
.append(" CUR: ").append(current)
.append(" PEN: ").append(pending)
.append(" GAR: ").append(guaranteed)
.append(" NORM: ").append(normalizedGuarantee)
.append(" IDEAL_ASSIGNED: ").append(idealAssigned)
.append(" IDEAL_PREEMPT: ").append(toBePreempted)
.append(" ACTUAL_PREEMPT: ").append(actuallyPreempted)
.append(" UNTOUCHABLE: ").append(untouchableExtra)
.append(" PREEMPTABLE: ").append(preemptableExtra)
.append("\n");
return sb.toString();
}
public void printAll() {
LOG.info(this.toString());
for (TempQueue sub : this.getChildren()) {
sub.printAll();
}
}
public void assignPreemption(float scalingFactor,
ResourceCalculator rc, Resource clusterResource) {
if (Resources.greaterThan(rc, clusterResource, current, idealAssigned)) {
toBePreempted = Resources.multiply(
Resources.subtract(current, idealAssigned), scalingFactor);
LOG.info("assignPreemption queue "+queueName+" toBePreempted "+toBePreempted);
} else {
toBePreempted = Resource.newInstance(0, 0);
}
}
void appendLogString(StringBuilder sb) {
sb.append("queuename").append(queueName).append(", ")
.append("current memory").append(current.getMemory()).append(", ")
.append("current core").append(current.getVirtualCores()).append(", ")
.append("pending memory").append(pending.getMemory()).append(", ")
.append("pending cores").append(pending.getVirtualCores()).append(", ")
.append("guarante memory").append(guaranteed.getMemory()).append(", ")
.append("guarante cores").append(guaranteed.getVirtualCores()).append(", ")
.append("idealized memory").append(idealAssigned.getMemory()).append(", ")
.append("idealized cores").append(idealAssigned.getVirtualCores()).append(", ")
.append("preempt memory").append(toBePreempted.getMemory()).append(", ")
.append("preempt cores").append(toBePreempted.getVirtualCores() ).append(", ")
.append("actual memory").append(actuallyPreempted.getMemory()).append(", ")
.append("actual cores").append(actuallyPreempted.getVirtualCores());
}
}
static class TQComparator implements Comparator<TempQueue> {
private ResourceCalculator rc;
private Resource clusterRes;
TQComparator(ResourceCalculator rc, Resource clusterRes) {
this.rc = rc;
this.clusterRes = clusterRes;
}
@Override
public int compare(TempQueue tq1, TempQueue tq2) {
if (getIdealPctOfGuaranteed(tq1) < getIdealPctOfGuaranteed(tq2)) {
return -1;
}
if (getIdealPctOfGuaranteed(tq1) > getIdealPctOfGuaranteed(tq2)) {
return 1;
}
return 0;
}
// Calculates idealAssigned / guaranteed
// TempQueues with 0 guarantees are always considered the most over
// capacity and therefore considered last for resources.
private double getIdealPctOfGuaranteed(TempQueue q) {
double pctOver = Integer.MAX_VALUE;
if (q != null && Resources.greaterThan(
rc, clusterRes, q.guaranteed, Resources.none())) {
pctOver =
Resources.divide(rc, clusterRes, q.idealAssigned, q.guaranteed);
}
return (pctOver);
}
}
}
| hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.PriorityQueue;
import java.util.Set;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.hash.Hash;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingEditPolicy;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
import org.apache.hadoop.yarn.util.Clock;
import org.apache.hadoop.yarn.util.SystemClock;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import com.google.common.annotations.VisibleForTesting;
/**
* This class implement a {@link SchedulingEditPolicy} that is designed to be
* paired with the {@code CapacityScheduler}. At every invocation of {@code
* editSchedule()} it computes the ideal amount of resources assigned to each
* queue (for each queue in the hierarchy), and determines whether preemption
* is needed. Overcapacity is distributed among queues in a weighted fair manner,
* where the weight is the amount of guaranteed capacity for the queue.
* Based on this ideal assignment it determines whether preemption is required
* and select a set of containers from each application that would be killed if
* the corresponding amount of resources is not freed up by the application.
*
* If not in {@code observeOnly} mode, it triggers preemption requests via a
* {@link ContainerPreemptEvent} that the {@code ResourceManager} will ensure
* to deliver to the application (or to execute).
*
* If the deficit of resources is persistent over a long enough period of time
* this policy will trigger forced termination of containers (again by generating
* {@link ContainerPreemptEvent}).
*/
public class ProportionalCapacityPreemptionPolicy implements SchedulingEditPolicy {
private static final Log LOG =
LogFactory.getLog(ProportionalCapacityPreemptionPolicy.class);
/** If true, run the policy but do not affect the cluster with preemption and
* kill events. */
public static final String OBSERVE_ONLY =
"yarn.resourcemanager.monitor.capacity.preemption.observe_only";
/** Time in milliseconds between invocations of this policy */
public static final String MONITORING_INTERVAL =
"yarn.resourcemanager.monitor.capacity.preemption.monitoring_interval";
/** Time in milliseconds between requesting a preemption from an application
* and killing the container. */
public static final String WAIT_TIME_BEFORE_KILL =
"yarn.resourcemanager.monitor.capacity.preemption.max_wait_before_kill";
/** Maximum percentage of resources preempted in a single round. By
* controlling this value one can throttle the pace at which containers are
* reclaimed from the cluster. After computing the total desired preemption,
* the policy scales it back within this limit. */
public static final String TOTAL_PREEMPTION_PER_ROUND =
"yarn.resourcemanager.monitor.capacity.preemp .tion.total_preemption_per_round";
/** Maximum amount of resources above the target capacity ignored for
* preemption. This defines a deadzone around the target capacity that helps
* prevent thrashing and oscillations around the computed target balance.
* High values would slow the time to capacity and (absent natural
* completions) it might prevent convergence to guaranteed capacity. */
public static final String MAX_IGNORED_OVER_CAPACITY =
"yarn.resourcemanager.monitor.capacity.preemption.max_ignored_over_capacity";
/**
* Given a computed preemption target, account for containers naturally
* expiring and preempt only this percentage of the delta. This determines
* the rate of geometric convergence into the deadzone ({@link
* #MAX_IGNORED_OVER_CAPACITY}). For example, a termination factor of 0.5
* will reclaim almost 95% of resources within 5 * {@link
* #WAIT_TIME_BEFORE_KILL}, even absent natural termination. */
public static final String NATURAL_TERMINATION_FACTOR =
"yarn.resourcemanager.monitor.capacity.preemption.natural_termination_factor";
public static final int PR_NUMBER = 2;
// the dispatcher to send preempt and kill events
public EventHandler<ContainerPreemptEvent> dispatcher;
private final Clock clock;
private double maxIgnoredOverCapacity;
private long maxWaitTime;
private CapacityScheduler scheduler;
private long monitoringInterval;
private final Map<RMContainer,Long> preempted =
new HashMap<RMContainer,Long>();
private ResourceCalculator rc;
private float percentageClusterPreemptionAllowed;
private double naturalTerminationFactor;
private boolean observeOnly;
private Map<NodeId, Set<String>> labels;
private boolean isSuspended = true;
public ProportionalCapacityPreemptionPolicy() {
clock = new SystemClock();
}
public ProportionalCapacityPreemptionPolicy(Configuration config,
EventHandler<ContainerPreemptEvent> dispatcher,
CapacityScheduler scheduler) {
this(config, dispatcher, scheduler, new SystemClock());
}
public ProportionalCapacityPreemptionPolicy(Configuration config,
EventHandler<ContainerPreemptEvent> dispatcher,
CapacityScheduler scheduler, Clock clock) {
init(config, dispatcher, scheduler);
this.clock = clock;
}
public void init(Configuration config,
EventHandler<ContainerPreemptEvent> disp,
PreemptableResourceScheduler sched) {
LOG.info("Preemption monitor:" + this.getClass().getCanonicalName());
assert null == scheduler : "Unexpected duplicate call to init";
if (!(sched instanceof CapacityScheduler)) {
throw new YarnRuntimeException("Class " +
sched.getClass().getCanonicalName() + " not instance of " +
CapacityScheduler.class.getCanonicalName());
}
dispatcher = disp;
scheduler = (CapacityScheduler) sched;
maxIgnoredOverCapacity = config.getDouble(MAX_IGNORED_OVER_CAPACITY, 0.1);
naturalTerminationFactor =
config.getDouble(NATURAL_TERMINATION_FACTOR, 0.2);
maxWaitTime = config.getLong(WAIT_TIME_BEFORE_KILL, 15000);
monitoringInterval = config.getLong(MONITORING_INTERVAL, 3000);
percentageClusterPreemptionAllowed =
config.getFloat(TOTAL_PREEMPTION_PER_ROUND, (float) 0.1);
observeOnly = config.getBoolean(OBSERVE_ONLY, false);
rc = scheduler.getResourceCalculator();
labels = null;
}
@VisibleForTesting
public ResourceCalculator getResourceCalculator() {
return rc;
}
@Override
public void editSchedule() {
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
clusterResources = getNonLabeledResources(clusterResources);
setNodeLabels(scheduler.getRMContext().getNodeLabelManager()
.getNodeLabels());
containerBasedPreemptOrKill(root, clusterResources);
}
/**
* Setting Node Labels
*
* @param nodelabels
*/
public void setNodeLabels(Map<NodeId, Set<String>> nodelabels) {
labels = nodelabels;
}
/**
* This method returns all non labeled resources.
*
* @param clusterResources
* @return Resources
*/
private Resource getNonLabeledResources(Resource clusterResources) {
RMContext rmcontext = scheduler.getRMContext();
RMNodeLabelsManager lm = rmcontext.getNodeLabelManager();
Resource res = lm.getResourceByLabel(RMNodeLabelsManager.NO_LABEL,
clusterResources);
return res == null ? clusterResources : res;
}
/**
* This method selects and tracks containers to be preempted. If a container
* is in the target list for more than maxWaitTime it is killed.
*
* @param root the root of the CapacityScheduler queue hierarchy
* @param clusterResources the total amount of resources in the cluster
*/
private void containerBasedPreemptOrKill(CSQueue root,
Resource clusterResources) {
// extract a summary of the queues from scheduler
TempQueue tRoot;
synchronized (scheduler) {
tRoot = cloneQueues(root, clusterResources);
}
// compute the ideal distribution of resources among queues
// updates cloned queues state accordingly
tRoot.idealAssigned = tRoot.guaranteed;
Resource totalPreemptionAllowed = Resources.multiply(clusterResources,
percentageClusterPreemptionAllowed);
List<TempQueue> queues =
recursivelyComputeIdealAssignment(tRoot, totalPreemptionAllowed);
// based on ideal allocation select containers to be preempted from each
// queue and each application
Map<ApplicationAttemptId,Map<RMContainer,Resource>> toPreempt =
getContainersToPreempt(queues, clusterResources);
if (LOG.isDebugEnabled())
{
logToCSV(queues);
}
// if we are in observeOnly mode return before any action is taken
if (observeOnly) {
return;
}
// preempt (or kill) the selected containers
for (Map.Entry<ApplicationAttemptId,Map<RMContainer,Resource>> e
: toPreempt.entrySet()) {
for (Map.Entry<RMContainer,Resource> cr : e.getValue().entrySet()) {
// if we tried to preempt this for more than maxWaitTime
RMContainer container = cr.getKey();
Resource resource = cr.getValue();
if (preempted.get(container) != null &&
preempted.get(container) + maxWaitTime < clock.getTime()) {
// suspend it
LOG.info("get container "+container.getContainerId()+" to suspend resource is "
+resource);
if(this.isSuspended){
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.SUSPEND_CONTAINER,resource));
}else{
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.KILL_CONTAINER,container.getContainer().getResource()));
}
preempted.remove(container);
} else {
//otherwise just send preemption events
dispatcher.handle(new ContainerPreemptEvent(e.getKey(), container,
ContainerPreemptEventType.PREEMPT_CONTAINER,resource));
if (preempted.get(container) == null) {
preempted.put(container, clock.getTime());
}
}
}
}
// Keep the preempted list clean
for (Iterator<RMContainer> i = preempted.keySet().iterator(); i.hasNext();){
RMContainer id = i.next();
// garbage collect containers that are irrelevant for preemption
if (preempted.get(id) + 2 * maxWaitTime < clock.getTime()) {
i.remove();
}
}
}
/**
* This method recursively computes the ideal assignment of resources to each
* level of the hierarchy. This ensures that leafs that are over-capacity but
* with parents within capacity will not be preempted. Preemptions are allowed
* within each subtree according to local over/under capacity.only return leaf nodes for this function
* 把所有的子queue全放在一个List里面,这里并不去区分层级关系
* @param root the root of the cloned queue hierachy
* @param totalPreemptionAllowed maximum amount of preemption allowed
* @return a list of leaf queues updated with preemption targets
*/
private List<TempQueue> recursivelyComputeIdealAssignment(
TempQueue root, Resource totalPreemptionAllowed) {
List<TempQueue> leafs = new ArrayList<TempQueue>();
if (root.getChildren() != null &&
root.getChildren().size() > 0) {
// compute ideal distribution at this level
computeIdealResourceDistribution(rc, root.getChildren(),
totalPreemptionAllowed, root.idealAssigned);
// compute recursively for lower levels and build list of leafs
for(TempQueue t : root.getChildren()) {
leafs.addAll(recursivelyComputeIdealAssignment(t, totalPreemptionAllowed));
}
} else {
// we are in a leaf nothing to do, just return yourself
return Collections.singletonList(root);
}
return leafs;
}
/**
* This method computes (for a single level in the tree, passed as a {@code
* List<TempQueue>}) the ideal assignment of resources. This is done
* recursively to allocate capacity fairly across all queues with pending
* demands. It terminates when no resources are left to assign, or when all
* demand is satisfied.
*
* @param rc resource calculator
* @param queues a list of cloned queues to be assigned capacity to (this is
* an out param)
* @param totalPreemptionAllowed total amount of preemption we allow
* @param tot_guarant the amount of capacity assigned to this pool of queues
*/
private void computeIdealResourceDistribution(ResourceCalculator rc,
List<TempQueue> queues, Resource totalPreemptionAllowed, Resource tot_guarant) {
// qAlloc tracks currently active queues (will decrease progressively as
// demand is met)
List<TempQueue> qAlloc = new ArrayList<TempQueue>(queues);
// unassigned tracks how much resources are still to assign, initialized
// with the total capacity for this set of queues
Resource unassigned = Resources.clone(tot_guarant);
LOG.info("computedIdealResourceDistribution: tot_guaran "+unassigned);
// group queues based on whether they have non-zero guaranteed capacity
Set<TempQueue> nonZeroGuarQueues = new HashSet<TempQueue>();
Set<TempQueue> zeroGuarQueues = new HashSet<TempQueue>();
for (TempQueue q : qAlloc) {
if (Resources
.greaterThan(rc, tot_guarant, q.guaranteed, Resources.none())) {
nonZeroGuarQueues.add(q);
} else {
zeroGuarQueues.add(q);
}
}
// first compute the allocation as a fixpoint based on guaranteed capacity
computeFixpointAllocation(rc, tot_guarant, nonZeroGuarQueues, unassigned,
false);
// if any capacity is left unassigned, distributed among zero-guarantee
// queues uniformly (i.e., not based on guaranteed capacity, as this is zero)
if (!zeroGuarQueues.isEmpty()
&& Resources.greaterThan(rc, tot_guarant, unassigned, Resources.none())) {
computeFixpointAllocation(rc, tot_guarant, zeroGuarQueues, unassigned,
true);
}
// based on ideal assignment computed above and current assignment we derive
// how much preemption is required overall,this is resource that are preemptable
Resource totPreemptionNeeded = Resource.newInstance(0, 0);
for (TempQueue t:queues) {
if (Resources.greaterThan(rc, tot_guarant, t.current, t.idealAssigned)) {
Resources.addTo(totPreemptionNeeded,
Resources.subtract(t.current, t.idealAssigned));
}
}
// if we need to preempt more than is allowed, compute a factor (0<f<1)
// that is used to scale down how much we ask back from each queue
float scalingFactor = 1.0F;
if (Resources.greaterThan(rc, tot_guarant,
totPreemptionNeeded, totalPreemptionAllowed)) {
scalingFactor = Resources.divide(rc, tot_guarant,
totalPreemptionAllowed, totPreemptionNeeded);
}
LOG.info("computeIdealResourceDistribution preemption allowed: "+totalPreemptionAllowed);
LOG.info("computeIdealResourceDistribution preemption needed : "+totPreemptionNeeded);
LOG.info("computeIdealResourceDistribution scalingFactor : "+scalingFactor);
// assign to each queue the amount of actual preemption based on local
// information of ideal preemption and scaling factor
for (TempQueue t : queues) {
t.assignPreemption(scalingFactor, rc, tot_guarant);
}
if (LOG.isDebugEnabled()) {
long time = clock.getTime();
for (TempQueue t : queues) {
LOG.debug(time + ": " + t);
}
}
}
/**
* Given a set of queues compute the fix-point distribution of unassigned
* resources among them. As pending request of a queue are exhausted, the
* queue is removed from the set and remaining capacity redistributed among
* remaining queues. The distribution is weighted based on guaranteed
* capacity, unless asked to ignoreGuarantee, in which case resources are
* distributed uniformly.
*/
private void computeFixpointAllocation(ResourceCalculator rc,
Resource tot_guarant, Collection<TempQueue> qAlloc, Resource unassigned,
boolean ignoreGuarantee) {
// Prior to assigning the unused resources, process each queue as follows:
// If current > guaranteed, idealAssigned = guaranteed + untouchable extra
// Else idealAssigned = current;
// Subtract idealAssigned resources from unassigned.
// If the queue has all of its needs met (that is, if
// idealAssigned >= current + pending), remove it from consideration.
// Sort queues from most under-guaranteed to most over-guaranteed.
TQComparator tqComparator = new TQComparator(rc, tot_guarant);
PriorityQueue<TempQueue> orderedByNeed =
new PriorityQueue<TempQueue>(10,tqComparator);
for (Iterator<TempQueue> i = qAlloc.iterator(); i.hasNext();) {
TempQueue q = i.next();
if (Resources.greaterThan(rc, tot_guarant, q.current, q.guaranteed)) {
q.idealAssigned = Resources.add(q.guaranteed, q.untouchableExtra);
} else {
q.idealAssigned = Resources.clone(q.current);
}
LOG.info("computeFixpointAllocation q :"+q.queueName+"idealAssigned: "+q.idealAssigned);
Resources.subtractFrom(unassigned, q.idealAssigned);
// If idealAssigned < (current + pending), q needs more resources, so
// add it to the list of underserved queues, ordered by need.
Resource curPlusPend = Resources.add(q.current, q.pending);
LOG.info("omputeFixpointAllocation q :"+q.queueName+" curPusPend: "+curPlusPend);
if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) {
orderedByNeed.add(q);
LOG.info("computeFixpointAllocation q: "+q.queueName+"needs more resource: "+q.pending);
}
}
LOG.info("computeFixpointAllocation unused resource: "+unassigned);
//assign all cluster resources until no more demand, or no resources are left
while (!orderedByNeed.isEmpty()
&& Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) {
Resource wQassigned = Resource.newInstance(0, 0);
// we compute normalizedGuarantees capacity based on currently active
// queues
resetCapacity(rc, unassigned, orderedByNeed, ignoreGuarantee);
// For each underserved queue (or set of queues if multiple are equally
// underserved), offer its share of the unassigned resources based on its
// normalized guarantee. After the offer, if the queue is not satisfied,
// place it back in the ordered list of queues, recalculating its place
// in the order of most under-guaranteed to most over-guaranteed. In this
// way, the most underserved queue(s) are always given resources first.
Collection<TempQueue> underserved =
getMostUnderservedQueues(orderedByNeed, tqComparator);
for (Iterator<TempQueue> i = underserved.iterator(); i.hasNext();) {
TempQueue sub = i.next();
//the share of this queue based on unassigned resource
Resource wQavail = Resources.multiplyAndNormalizeUp(rc,
unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1));
LOG.info("computeFixpointAllocation q: "+sub.queueName+" wQavail: "+wQavail);
Resource wQidle = sub.offer(wQavail, rc, tot_guarant);
Resource wQdone = Resources.subtract(wQavail, wQidle);
//wQdone is 0 说明 说明wQavail已经被分配完
if (Resources.greaterThan(rc, tot_guarant,
wQdone, Resources.none())) {
// The queue is still asking for more. Put it back in the priority
// queue, recalculating its order based on need.
orderedByNeed.add(sub);
}
Resources.addTo(wQassigned, wQdone);
}
LOG.info("computeFixpointAllocation inloop unused resource: "+unassigned);
Resources.subtractFrom(unassigned, wQassigned);
}
}
// Take the most underserved TempQueue (the one on the head). Collect and
// return the list of all queues that have the same idealAssigned
// percentage of guaranteed. the less this value, the more underserved this queue
protected Collection<TempQueue> getMostUnderservedQueues(
PriorityQueue<TempQueue> orderedByNeed, TQComparator tqComparator) {
ArrayList<TempQueue> underserved = new ArrayList<TempQueue>();
while (!orderedByNeed.isEmpty()) {
TempQueue q1 = orderedByNeed.remove();
underserved.add(q1);
TempQueue q2 = orderedByNeed.peek();
// q1's pct of guaranteed won't be larger than q2's. If it's less, then
// return what has already been collected. Otherwise, q1's pct of
// guaranteed == that of q2, so add q2 to underserved list during the
// next pass.
if (q2 == null || tqComparator.compare(q1,q2) < 0) {
return underserved;
}
}
return underserved;
}
/**
* Computes a normalizedGuaranteed capacity based on active queues
* @param rc resource calculator
* @param clusterResource the total amount of resources in the cluster
* @param queues the list of queues to consider
*/
private void resetCapacity(ResourceCalculator rc, Resource clusterResource,
Collection<TempQueue> queues, boolean ignoreGuar) {
Resource activeCap = Resource.newInstance(0, 0);
if (ignoreGuar) {
for (TempQueue q : queues) {
q.normalizedGuarantee = (float) 1.0f / ((float) queues.size());
}
} else {
for (TempQueue q : queues) {
Resources.addTo(activeCap, q.guaranteed);
}
for (TempQueue q : queues) {
q.normalizedGuarantee = Resources.divide(rc, clusterResource, q.guaranteed, activeCap);
LOG.info("resetCapacity q: "+q.queueName+" normalizedGuarantee: "+q.normalizedGuarantee);
}
}
}
/**
* Based a resource preemption target drop reservations of containers and
* if necessary select containers for preemption from applications in each
* over-capacity queue. It uses {@link #NATURAL_TERMINATION_FACTOR} to
* account for containers that will naturally complete.
*
* @param queues set of leaf queues to preempt from
* @param clusterResource total amount of cluster resources
* @return a map of applciationID to set of containers to preempt
*/
private Map<ApplicationAttemptId,Map<RMContainer,Resource>> getContainersToPreempt(
List<TempQueue> queues, Resource clusterResource) {
Map<ApplicationAttemptId, Map<RMContainer,Resource>> preemptMap =
new HashMap<ApplicationAttemptId, Map<RMContainer,Resource>>();
List<RMContainer> skippedAMContainerlist = new ArrayList<RMContainer>();
for (TempQueue qT : queues) {
if (qT.preemptionDisabled && qT.leafQueue != null) {
if (LOG.isDebugEnabled()) {
if (Resources.greaterThan(rc, clusterResource,
qT.toBePreempted, Resource.newInstance(0, 0))) {
LOG.info("Tried to preempt the following "
+ "resources from non-preemptable queue: "
+ qT.queueName + " - Resources: " + qT.toBePreempted);
}
}
continue;
}
// we act only if we are violating balance by more than
// maxIgnoredOverCapacity
if (Resources.greaterThan(rc, clusterResource, qT.current,
Resources.multiply(qT.guaranteed, 1.0 + maxIgnoredOverCapacity))) {
// we introduce a dampening factor naturalTerminationFactor that
// accounts for natural termination of containers
Resource resToObtain =
Resources.multiply(qT.toBePreempted, naturalTerminationFactor);
Resource skippedAMSize = Resource.newInstance(0, 0);
LOG.info("getContainersToPreempt queue: "+qT.queueName);
LOG.info("getContainersToPreempt factor: "+naturalTerminationFactor);
LOG.info("getContainersToPreempt obatain: "+resToObtain);
// lock the leafqueue while we scan applications and unreserve
synchronized (qT.leafQueue) {
//what is the descending order
NavigableSet<FiCaSchedulerApp> ns =
(NavigableSet<FiCaSchedulerApp>) qT.leafQueue.getApplications();
Iterator<FiCaSchedulerApp> desc = ns.descendingIterator();
qT.actuallyPreempted = Resources.clone(resToObtain);
while (desc.hasNext()) {
FiCaSchedulerApp fc = desc.next();
if (Resources.lessThanOrEqual(rc, clusterResource, resToObtain,
Resources.none())) {
break;
}
LOG.info("now try to preempt applicatin:"+fc.getApplicationId());
preemptMap.put(
fc.getApplicationAttemptId(),
preemptFrom(fc, clusterResource, resToObtain,
skippedAMContainerlist, skippedAMSize));
}
//we will never preempt am resource
// Resource maxAMCapacityForThisQueue = Resources.multiply(
// Resources.multiply(clusterResource,
// qT.leafQueue.getAbsoluteCapacity()),
// qT.leafQueue.getMaxAMResourcePerQueuePercent());
// Can try preempting AMContainers (still saving atmost
// maxAMCapacityForThisQueue AMResource's) if more resources are
// required to be preempted from this Queue.
//preemptAMContainers(clusterResource, preemptMap,
// skippedAMContainerlist, resToObtain, skippedAMSize,
// maxAMCapacityForThisQueue);
}
}
}
return preemptMap;
}
/**
* As more resources are needed for preemption, saved AMContainers has to be
* rescanned. Such AMContainers can be preempted based on resToObtain, but
* maxAMCapacityForThisQueue resources will be still retained.
*
* @param clusterResource
* @param preemptMap
* @param skippedAMContainerlist
* @param resToObtain
* @param skippedAMSize
* @param maxAMCapacityForThisQueue
*/
private void preemptAMContainers(Resource clusterResource,
Map<ApplicationAttemptId, Set<RMContainer>> preemptMap,
List<RMContainer> skippedAMContainerlist, Resource resToObtain,
Resource skippedAMSize, Resource maxAMCapacityForThisQueue) {
for (RMContainer c : skippedAMContainerlist) {
// Got required amount of resources for preemption, can stop now
if (Resources.lessThanOrEqual(rc, clusterResource, resToObtain,
Resources.none())) {
break;
}
// Once skippedAMSize reaches down to maxAMCapacityForThisQueue,
// container selection iteration for preemption will be stopped.
if (Resources.lessThanOrEqual(rc, clusterResource, skippedAMSize,
maxAMCapacityForThisQueue)) {
break;
}
Set<RMContainer> contToPrempt = preemptMap.get(c
.getApplicationAttemptId());
if (null == contToPrempt) {
contToPrempt = new HashSet<RMContainer>();
preemptMap.put(c.getApplicationAttemptId(), contToPrempt);
}
contToPrempt.add(c);
Resources.subtractFrom(resToObtain, c.getContainer().getResource());
Resources.subtractFrom(skippedAMSize, c.getContainer()
.getResource());
}
skippedAMContainerlist.clear();
}
/**
* Given a target preemption for a specific application, select containers
* to preempt (after unreserving all reservation for that app).
*
* @param app
* @param clusterResource
* @param rsrcPreempt
* @return Map<RMContainer,Resource> mapping from container to resource
*/
private Map<RMContainer,Resource> preemptFrom(FiCaSchedulerApp app,
Resource clusterResource, Resource rsrcPreempt,
List<RMContainer> skippedAMContainerlist, Resource skippedAMSize) {
Map<RMContainer,Resource> ret = new HashMap<RMContainer,Resource>();
ApplicationAttemptId appId = app.getApplicationAttemptId();
// first drop reserved containers towards rsrcPreempt
List<RMContainer> reservations =
new ArrayList<RMContainer>(app.getReservedContainers());
for (RMContainer c : reservations) {
if (Resources.lessThanOrEqual(rc, clusterResource,
rsrcPreempt, Resources.none())) {
return ret;
}
if (!observeOnly) {
dispatcher.handle(new ContainerPreemptEvent(appId, c,
ContainerPreemptEventType.DROP_RESERVATION, c.getContainer().getResource()));
}
Resources.subtractFrom(rsrcPreempt, c.getContainer().getResource());
}
// if more resources are to be freed go through all live containers in
// reverse priority and reverse allocation order and mark them for
// preemption
List<RMContainer> containers =
new ArrayList<RMContainer>(((FiCaSchedulerApp)app).getUnPreemtedContainers());
sortContainers(containers);
for (RMContainer c : containers) {
if (Resources.lessThanOrEqual(rc, clusterResource,
rsrcPreempt, Resources.none())) {
return ret;
}
// Skip AM Container from preemption for now.
if (c.isAMContainer()) {
skippedAMContainerlist.add(c);
Resources.addTo(skippedAMSize, c.getContainer().getResource());
continue;
}
// skip Labeled resource
if(isLabeledContainer(c)){
continue;
}
//compute preempted resource this round
Resource preempteThisTime = Resources.mins(rc, clusterResource,
rsrcPreempt, c.getSRResourceUnit());
LOG.info("get preempted Resource: "+preempteThisTime);
ret.put(c,preempteThisTime);
//substract preempted resource
Resources.subtractFrom(rsrcPreempt, preempteThisTime);
}
return ret;
}
/**
* Checking if given container is a labeled container
*
* @param c
* @return true/false
*/
private boolean isLabeledContainer(RMContainer c) {
return labels.containsKey(c.getAllocatedNode());
}
/**
* Compare by reversed priority order first, and then reversed containerId
* order
* @param containers
*/
@VisibleForTesting
static void sortContainers(List<RMContainer> containers){
Collections.sort(containers, new Comparator<RMContainer>() {
@Override
public int compare(RMContainer a, RMContainer b) {
Comparator<Priority> c = new org.apache.hadoop.yarn.server
.resourcemanager.resource.Priority.Comparator();
int priorityComp = c.compare(b.getContainer().getPriority(),
a.getContainer().getPriority());
if (priorityComp != 0) {
return priorityComp;
}
return b.getContainerId().compareTo(a.getContainerId());
}
});
}
@Override
public long getMonitoringInterval() {
return monitoringInterval;
}
@Override
public String getPolicyName() {
return "ProportionalCapacityPreemptionPolicy";
}
/**
* This method walks a tree of CSQueue and clones the portion of the state
* relevant for preemption in TempQueue(s). It also maintains a pointer to
* the leaves. Finally it aggregates pending resources in each queue and rolls
* it up to higher levels.
*
* @param root the root of the CapacityScheduler queue hierarchy
* @param clusterResources the total amount of resources in the cluster
* @return the root of the cloned queue hierarchy
*/
private TempQueue cloneQueues(CSQueue root, Resource clusterResources) {
TempQueue ret;
synchronized (root) {
LOG.info("cloneQueues enter");
String queueName = root.getQueueName();
float absUsed = root.getAbsoluteUsedCapacity();
float absCap = root.getAbsoluteCapacity();
float absMaxCap = root.getAbsoluteMaximumCapacity();
boolean preemptionDisabled = root.getPreemptionDisabled();
//Resource current = Resources.multiply(clusterResources, absUsed);
Resource current = root.getUsedResources();
Resource guaranteed = Resources.multiply(clusterResources, absCap);
Resource maxCapacity = Resources.multiply(clusterResources, absMaxCap);
LOG.info("cloneQueues current queue: "+queueName+" usedResource: "+root.getUsedResources());
LOG.info("cloneQueues current queue: "+queueName+" ratiodResource: "+Resources.multiply(clusterResources, absUsed));
Resource extra = Resource.newInstance(0, 0);
if (Resources.greaterThan(rc, clusterResources, current, guaranteed)) {
extra = Resources.subtract(current, guaranteed);
}
if (root instanceof LeafQueue) {
LeafQueue l = (LeafQueue) root;
Resource pending = l.getTotalResourcePending();
ret = new TempQueue(queueName, current, pending, guaranteed,
maxCapacity, preemptionDisabled);
if (preemptionDisabled) {
ret.untouchableExtra = extra;
} else {
ret.preemptableExtra = extra;
}
ret.setLeafQueue(l);
} else {
Resource pending = Resource.newInstance(0, 0);
ret = new TempQueue(root.getQueueName(), current, pending, guaranteed,
maxCapacity, false);
Resource childrensPreemptable = Resource.newInstance(0, 0);
for (CSQueue c : root.getChildQueues()) {
TempQueue subq = cloneQueues(c, clusterResources);
Resources.addTo(childrensPreemptable, subq.preemptableExtra);
ret.addChild(subq);
}
// untouchableExtra = max(extra - childrenPreemptable, 0)
if (Resources.greaterThanOrEqual(
rc, clusterResources, childrensPreemptable, extra)) {
//it means there are some extra resource in child node are marked untouchable.
ret.untouchableExtra = Resource.newInstance(0, 0);
} else {
ret.untouchableExtra =
Resources.subtractFrom(extra, childrensPreemptable);
}
}
}
return ret;
}
// simple printout function that reports internal queue state (useful for
// plotting)
private void logToCSV(List<TempQueue> unorderedqueues){
List<TempQueue> queues = new ArrayList<TempQueue>(unorderedqueues);
Collections.sort(queues, new Comparator<TempQueue>(){
@Override
public int compare(TempQueue o1, TempQueue o2) {
return o1.queueName.compareTo(o2.queueName);
}});
String queueState = " QUEUESTATE: " + clock.getTime();
StringBuilder sb = new StringBuilder();
sb.append(queueState);
for (TempQueue tq : queues) {
sb.append(", ");
tq.appendLogString(sb);
}
LOG.info(sb.toString());
}
/**
* Temporary data-structure tracking resource availability, pending resource
* need, current utilization. Used to clone {@link CSQueue}.
*/
static class TempQueue {
final String queueName;
final Resource current;
final Resource pending;
final Resource guaranteed;
final Resource maxCapacity;
Resource idealAssigned;
Resource toBePreempted;
Resource actuallyPreempted;
Resource untouchableExtra;
Resource preemptableExtra;
double normalizedGuarantee;
final ArrayList<TempQueue> children;
LeafQueue leafQueue;
boolean preemptionDisabled;
TempQueue(String queueName, Resource current, Resource pending,
Resource guaranteed, Resource maxCapacity, boolean preemptionDisabled) {
this.queueName = queueName;
this.current = current;
this.pending = pending;
this.guaranteed = guaranteed;
this.maxCapacity = maxCapacity;
this.idealAssigned = Resource.newInstance(0, 0);
this.actuallyPreempted = Resource.newInstance(0, 0);
this.toBePreempted = Resource.newInstance(0, 0);
this.normalizedGuarantee = Float.NaN;
this.children = new ArrayList<TempQueue>();
//both leaf and parent node may have untouchable resource
this.untouchableExtra = Resource.newInstance(0, 0);
//only leaf node has preemptable extra
this.preemptableExtra = Resource.newInstance(0, 0);
this.preemptionDisabled = preemptionDisabled;
}
public void setLeafQueue(LeafQueue l){
assert children.size() == 0;
this.leafQueue = l;
}
/**
* When adding a child we also aggregate its pending resource needs.
* @param q the child queue to add to this queue
*/
public void addChild(TempQueue q) {
assert leafQueue == null;
children.add(q);
Resources.addTo(pending, q.pending);
}
public void addChildren(ArrayList<TempQueue> queues) {
assert leafQueue == null;
children.addAll(queues);
}
public ArrayList<TempQueue> getChildren(){
return children;
}
// This function "accepts" all the resources it can (pending) and return
// the unused ones
Resource offer(Resource avail, ResourceCalculator rc,
Resource clusterResource) {
Resource absMaxCapIdealAssignedDelta = Resources.componentwiseMax(
Resources.subtract(maxCapacity, idealAssigned),
Resource.newInstance(0, 0));
// remain = avail - min(avail, (max - assigned), (current + pending - assigned))
// we have bug here. in some case:
//(current + pending - assigned).core > avail.core
//(current + pending - assigned).memo < avail.memo
//so we get least cores of the three and least memory of the three
Resource accepted =
Resources.mins(rc, clusterResource,
absMaxCapIdealAssignedDelta,
Resources.mins(rc, clusterResource, avail, Resources.subtract(
Resources.add(current, pending), idealAssigned)));
Resource remain = Resources.subtract(avail, accepted);
Resources.addTo(idealAssigned, accepted);
LOG.info("queueName: "+queueName);
LOG.info("avaul: "+avail);
LOG.info("absMaxDelta: "+absMaxCapIdealAssignedDelta);
LOG.info("max: "+maxCapacity);
LOG.info("current: "+current);
LOG.info("pending: "+pending);
LOG.info("acceped: "+accepted);
LOG.info("ideal: "+idealAssigned);
return remain;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" NAME: " + queueName)
.append(" CUR: ").append(current)
.append(" PEN: ").append(pending)
.append(" GAR: ").append(guaranteed)
.append(" NORM: ").append(normalizedGuarantee)
.append(" IDEAL_ASSIGNED: ").append(idealAssigned)
.append(" IDEAL_PREEMPT: ").append(toBePreempted)
.append(" ACTUAL_PREEMPT: ").append(actuallyPreempted)
.append(" UNTOUCHABLE: ").append(untouchableExtra)
.append(" PREEMPTABLE: ").append(preemptableExtra)
.append("\n");
return sb.toString();
}
public void printAll() {
LOG.info(this.toString());
for (TempQueue sub : this.getChildren()) {
sub.printAll();
}
}
public void assignPreemption(float scalingFactor,
ResourceCalculator rc, Resource clusterResource) {
if (Resources.greaterThan(rc, clusterResource, current, idealAssigned)) {
toBePreempted = Resources.multiply(
Resources.subtract(current, idealAssigned), scalingFactor);
LOG.info("assignPreemption queue "+queueName+" toBePreempted "+toBePreempted);
} else {
toBePreempted = Resource.newInstance(0, 0);
}
}
void appendLogString(StringBuilder sb) {
sb.append("queuename").append(queueName).append(", ")
.append("current memory").append(current.getMemory()).append(", ")
.append("current core").append(current.getVirtualCores()).append(", ")
.append("pending memory").append(pending.getMemory()).append(", ")
.append("pending cores").append(pending.getVirtualCores()).append(", ")
.append("guarante memory").append(guaranteed.getMemory()).append(", ")
.append("guarante cores").append(guaranteed.getVirtualCores()).append(", ")
.append("idealized memory").append(idealAssigned.getMemory()).append(", ")
.append("idealized cores").append(idealAssigned.getVirtualCores()).append(", ")
.append("preempt memory").append(toBePreempted.getMemory()).append(", ")
.append("preempt cores").append(toBePreempted.getVirtualCores() ).append(", ")
.append("actual memory").append(actuallyPreempted.getMemory()).append(", ")
.append("actual cores").append(actuallyPreempted.getVirtualCores());
}
}
static class TQComparator implements Comparator<TempQueue> {
private ResourceCalculator rc;
private Resource clusterRes;
TQComparator(ResourceCalculator rc, Resource clusterRes) {
this.rc = rc;
this.clusterRes = clusterRes;
}
@Override
public int compare(TempQueue tq1, TempQueue tq2) {
if (getIdealPctOfGuaranteed(tq1) < getIdealPctOfGuaranteed(tq2)) {
return -1;
}
if (getIdealPctOfGuaranteed(tq1) > getIdealPctOfGuaranteed(tq2)) {
return 1;
}
return 0;
}
// Calculates idealAssigned / guaranteed
// TempQueues with 0 guarantees are always considered the most over
// capacity and therefore considered last for resources.
private double getIdealPctOfGuaranteed(TempQueue q) {
double pctOver = Integer.MAX_VALUE;
if (q != null && Resources.greaterThan(
rc, clusterRes, q.guaranteed, Resources.none())) {
pctOver =
Resources.divide(rc, clusterRes, q.idealAssigned, q.guaranteed);
}
return (pctOver);
}
}
}
| final debug 2
| hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java | final debug 2 | <ide><path>adoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java
<ide> // with the total capacity for this set of queues
<ide> Resource unassigned = Resources.clone(tot_guarant);
<ide>
<del> LOG.info("computedIdealResourceDistribution: tot_guaran "+unassigned);
<del>
<ide> // group queues based on whether they have non-zero guaranteed capacity
<ide> Set<TempQueue> nonZeroGuarQueues = new HashSet<TempQueue>();
<ide> Set<TempQueue> zeroGuarQueues = new HashSet<TempQueue>();
<ide> totalPreemptionAllowed, totPreemptionNeeded);
<ide> }
<ide>
<del> LOG.info("computeIdealResourceDistribution preemption allowed: "+totalPreemptionAllowed);
<del> LOG.info("computeIdealResourceDistribution preemption needed : "+totPreemptionNeeded);
<del> LOG.info("computeIdealResourceDistribution scalingFactor : "+scalingFactor);
<del>
<ide> // assign to each queue the amount of actual preemption based on local
<ide> // information of ideal preemption and scaling factor
<ide> for (TempQueue t : queues) {
<ide> q.idealAssigned = Resources.clone(q.current);
<ide> }
<ide>
<del> LOG.info("computeFixpointAllocation q :"+q.queueName+"idealAssigned: "+q.idealAssigned);
<del>
<ide> Resources.subtractFrom(unassigned, q.idealAssigned);
<ide> // If idealAssigned < (current + pending), q needs more resources, so
<ide> // add it to the list of underserved queues, ordered by need.
<ide> Resource curPlusPend = Resources.add(q.current, q.pending);
<del> LOG.info("omputeFixpointAllocation q :"+q.queueName+" curPusPend: "+curPlusPend);
<ide>
<ide>
<ide> if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) {
<ide>
<ide> orderedByNeed.add(q);
<del> LOG.info("computeFixpointAllocation q: "+q.queueName+"needs more resource: "+q.pending);
<del> }
<del> }
<del>
<del> LOG.info("computeFixpointAllocation unused resource: "+unassigned);
<add>
<add> }
<add> }
<add>
<add>
<ide> //assign all cluster resources until no more demand, or no resources are left
<ide> while (!orderedByNeed.isEmpty()
<ide> && Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) {
<ide> //the share of this queue based on unassigned resource
<ide> Resource wQavail = Resources.multiplyAndNormalizeUp(rc,
<ide> unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1));
<del>
<del> LOG.info("computeFixpointAllocation q: "+sub.queueName+" wQavail: "+wQavail);
<del>
<add>
<ide> Resource wQidle = sub.offer(wQavail, rc, tot_guarant);
<ide> Resource wQdone = Resources.subtract(wQavail, wQidle);
<ide>
<ide> }
<ide> for (TempQueue q : queues) {
<ide> q.normalizedGuarantee = Resources.divide(rc, clusterResource, q.guaranteed, activeCap);
<del> LOG.info("resetCapacity q: "+q.queueName+" normalizedGuarantee: "+q.normalizedGuarantee);
<ide> }
<ide> }
<ide> }
<ide> Resource resToObtain =
<ide> Resources.multiply(qT.toBePreempted, naturalTerminationFactor);
<ide> Resource skippedAMSize = Resource.newInstance(0, 0);
<del> LOG.info("getContainersToPreempt queue: "+qT.queueName);
<del> LOG.info("getContainersToPreempt factor: "+naturalTerminationFactor);
<del> LOG.info("getContainersToPreempt obatain: "+resToObtain);
<ide> // lock the leafqueue while we scan applications and unreserve
<ide> synchronized (qT.leafQueue) {
<ide> //what is the descending order
<ide> skippedAMContainerlist, skippedAMSize));
<ide> }
<ide>
<add> //we allow preempt AM for kill based approach
<add> if(!isSuspended){
<ide> //we will never preempt am resource
<del> // Resource maxAMCapacityForThisQueue = Resources.multiply(
<del> // Resources.multiply(clusterResource,
<del> // qT.leafQueue.getAbsoluteCapacity()),
<del> // qT.leafQueue.getMaxAMResourcePerQueuePercent());
<del>
<del> // Can try preempting AMContainers (still saving atmost
<add> Resource maxAMCapacityForThisQueue = Resources.multiply(
<add> Resources.multiply(clusterResource,
<add> qT.leafQueue.getAbsoluteCapacity()),
<add> qT.leafQueue.getMaxAMResourcePerQueuePercent());
<add>
<add> //Can try preempting AMContainers (still saving atmost
<ide> // maxAMCapacityForThisQueue AMResource's) if more resources are
<ide> // required to be preempted from this Queue.
<del> //preemptAMContainers(clusterResource, preemptMap,
<del> // skippedAMContainerlist, resToObtain, skippedAMSize,
<del> // maxAMCapacityForThisQueue);
<add> preemptAMContainers(clusterResource, preemptMap,
<add> skippedAMContainerlist, resToObtain, skippedAMSize,
<add> maxAMCapacityForThisQueue);
<add> }
<ide> }
<ide> }
<ide> }
<ide> * @param maxAMCapacityForThisQueue
<ide> */
<ide> private void preemptAMContainers(Resource clusterResource,
<del> Map<ApplicationAttemptId, Set<RMContainer>> preemptMap,
<add> Map<ApplicationAttemptId, Map<RMContainer,Resource>> preemptMap,
<ide> List<RMContainer> skippedAMContainerlist, Resource resToObtain,
<ide> Resource skippedAMSize, Resource maxAMCapacityForThisQueue) {
<ide> for (RMContainer c : skippedAMContainerlist) {
<ide> maxAMCapacityForThisQueue)) {
<ide> break;
<ide> }
<del> Set<RMContainer> contToPrempt = preemptMap.get(c
<add> Map<RMContainer,Resource> contToPrempt = preemptMap.get(c
<ide> .getApplicationAttemptId());
<ide> if (null == contToPrempt) {
<del> contToPrempt = new HashSet<RMContainer>();
<add> contToPrempt = new HashMap<RMContainer,Resource>();
<ide> preemptMap.put(c.getApplicationAttemptId(), contToPrempt);
<ide> }
<del> contToPrempt.add(c);
<add> contToPrempt.put(c,c.getContainer().getResource());
<ide>
<ide> Resources.subtractFrom(resToObtain, c.getContainer().getResource());
<ide> Resources.subtractFrom(skippedAMSize, c.getContainer()
<ide> continue;
<ide> }
<ide>
<add> Resource preempteThisTime;
<add> if(isSuspended){
<ide> //compute preempted resource this round
<del> Resource preempteThisTime = Resources.mins(rc, clusterResource,
<add> preempteThisTime = Resources.mins(rc, clusterResource,
<ide> rsrcPreempt, c.getSRResourceUnit());
<add> }else{
<add>
<add> preempteThisTime = c.getContainer().getResource();
<add>
<add> }
<ide> LOG.info("get preempted Resource: "+preempteThisTime);
<ide>
<ide> ret.put(c,preempteThisTime);
<ide> float absMaxCap = root.getAbsoluteMaximumCapacity();
<ide> boolean preemptionDisabled = root.getPreemptionDisabled();
<ide>
<del>
<del> //Resource current = Resources.multiply(clusterResources, absUsed);
<del> Resource current = root.getUsedResources();
<add> Resource current;
<add>
<add> //differenciate the resource based on if it is suspended
<add> if(isSuspended){
<add> current = root.getUsedResources();
<add> }else{
<add> current = Resources.multiply(clusterResources, absUsed);
<add> }
<add>
<add>
<ide> Resource guaranteed = Resources.multiply(clusterResources, absCap);
<ide> Resource maxCapacity = Resources.multiply(clusterResources, absMaxCap);
<ide> |
|
Java | apache-2.0 | 2ed08904c5b61c99b81685916d048a7e1fac342b | 0 | ErnestOrt/Trampoline,ErnestOrt/Trampoline,ErnestOrt/Trampoline | package org.ernest.applications.trampoline.entities;
public class Microservice {
private String id;
private String name;
private String pomLocation;
private String gitLocation;
private String defaultPort;
private String actuatorPrefix;
private String vmArguments;
private BuildTools buildTool;
private Float version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPomLocation() {
return pomLocation;
}
public void setPomLocation(String pomLocation) {
this.pomLocation = pomLocation;
}
public String getDefaultPort() {
return defaultPort;
}
public void setDefaultPort(String defaultPort) {
this.defaultPort = defaultPort;
}
public String getActuatorPrefix() {
return actuatorPrefix;
}
public String getVmArguments() {
return vmArguments;
}
public void setVmArguments(String vmArguments) {
this.vmArguments = vmArguments;
}
public void setActuatorPrefix(String actuatorPrefix) {
this.actuatorPrefix = actuatorPrefix.replaceFirst("^/","");
}
public BuildTools getBuildTool() {
return buildTool;
}
public void setBuildTool(BuildTools buildTool) {
this.buildTool = buildTool;
}
public Float getVersion() {
return version;
}
public void setVersion(Float version) {
this.version = version;
}
public String getGitLocation() {
return gitLocation;
}
public void setGitLocation(String gitLocation) {
this.gitLocation = gitLocation;
}
@Override
public String toString() {
return "Microservice{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", pomLocation='" + pomLocation + '\'' +
", gitLocation='" + gitLocation + '\'' +
", defaultPort='" + defaultPort + '\'' +
", actuatorPrefix='" + actuatorPrefix + '\'' +
", vmArguments='" + vmArguments + '\'' +
", buildTool=" + buildTool +
", version=" + version +
'}';
}
} | trampoline/src/main/java/org/ernest/applications/trampoline/entities/Microservice.java | package org.ernest.applications.trampoline.entities;
public class Microservice {
private String id;
private String name;
private String pomLocation;
private String gitLocation;
private String defaultPort;
private String actuatorPrefix;
private String vmArguments;
private BuildTools buildTool;
private Float version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPomLocation() {
return pomLocation;
}
public void setPomLocation(String pomLocation) {
this.pomLocation = pomLocation;
}
public String getDefaultPort() {
return defaultPort;
}
public void setDefaultPort(String defaultPort) {
this.defaultPort = defaultPort;
}
public String getActuatorPrefix() {
return actuatorPrefix;
}
public String getVmArguments() {
return vmArguments;
}
public void setVmArguments(String vmArguments) {
this.vmArguments = vmArguments;
}
public void setActuatorPrefix(String actuatorPrefix) {
this.actuatorPrefix = actuatorPrefix;
}
public BuildTools getBuildTool() {
return buildTool;
}
public void setBuildTool(BuildTools buildTool) {
this.buildTool = buildTool;
}
public Float getVersion() {
return version;
}
public void setVersion(Float version) {
this.version = version;
}
public String getGitLocation() {
return gitLocation;
}
public void setGitLocation(String gitLocation) {
this.gitLocation = gitLocation;
}
@Override
public String toString() {
return "Microservice{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", pomLocation='" + pomLocation + '\'' +
", gitLocation='" + gitLocation + '\'' +
", defaultPort='" + defaultPort + '\'' +
", actuatorPrefix='" + actuatorPrefix + '\'' +
", vmArguments='" + vmArguments + '\'' +
", buildTool=" + buildTool +
", version=" + version +
'}';
}
} | Added regex to strip '/' from actuator prefix in setter
| trampoline/src/main/java/org/ernest/applications/trampoline/entities/Microservice.java | Added regex to strip '/' from actuator prefix in setter | <ide><path>rampoline/src/main/java/org/ernest/applications/trampoline/entities/Microservice.java
<ide> this.vmArguments = vmArguments;
<ide> }
<ide> public void setActuatorPrefix(String actuatorPrefix) {
<del> this.actuatorPrefix = actuatorPrefix;
<add> this.actuatorPrefix = actuatorPrefix.replaceFirst("^/","");
<ide> }
<ide>
<ide> public BuildTools getBuildTool() { |
|
Java | apache-2.0 | b8c08db871220b561ed67f851824dd953aba62e6 | 0 | google/ground-android,google/ground-android,google/ground-android | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gnd.ui;
import static com.google.android.gnd.ui.OnBottomSheetSlideBehavior.SheetSlideMetrics.scale;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gnd.R;
public class BottomSheetChromeBehavior extends OnBottomSheetSlideBehavior<ViewGroup> {
// TODO: Refactor transitions into "TransitionEffect" classes.
private static final float HIDE_SCRIM_THRESHOLD = 0.0f;
private static final float SHOW_SCRIM_THRESHOLD = 0.1f;
private static final float HIDE_ADD_BUTTON_THRESHOLD = 0.3f;
private static final float SHOW_ADD_BUTTON_THRESHOLD = 0.5f;
public BottomSheetChromeBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSheetScrolled(
CoordinatorLayout parent, ViewGroup layout, SheetSlideMetrics metrics) {
View scrim = layout.findViewById(R.id.bottom_sheet_bottom_inset_scrim);
View addRecordButton = layout.findViewById(R.id.add_record_btn);
ViewGroup toolbarWrapper = layout.findViewById(R.id.toolbar_wrapper);
ViewGroup toolbar = toolbarWrapper.findViewById(R.id.toolbar);
ViewGroup toolbarTitles = toolbarWrapper.findViewById(R.id.toolbar_titles_layout);
metrics.showWithSheet(scrim, HIDE_SCRIM_THRESHOLD, SHOW_SCRIM_THRESHOLD);
metrics.showWithSheet(addRecordButton, HIDE_ADD_BUTTON_THRESHOLD, SHOW_ADD_BUTTON_THRESHOLD);
toolbarWrapper.setBackgroundColor(layout.getResources().getColor(R.color.colorPrimary));
toolbarWrapper.setTranslationY(
scale(metrics.getVisibleRatio(), 0.3f, 0.5f, -toolbarWrapper.getHeight(), 0));
metrics.showWithSheet(toolbarWrapper.getBackground(), 0.9f, 1);
// Fade in toolbar text labels with sheet expansion.
float alpha = scale(metrics.getTop(), 0, toolbarWrapper.getHeight(), 1f, 0f);
toolbarTitles.setAlpha(alpha);
}
}
| gnd/src/main/java/com/google/android/gnd/ui/BottomSheetChromeBehavior.java | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gnd.ui;
import static com.google.android.gnd.ui.OnBottomSheetSlideBehavior.SheetSlideMetrics.scale;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gnd.R;
public class BottomSheetChromeBehavior extends OnBottomSheetSlideBehavior<ViewGroup> {
// TODO: Refactor transitions into "TransitionEffect" classes.
private static final float HIDE_SCRIM_THRESHOLD = 0.0f;
private static final float SHOW_SCRIM_THRESHOLD = 0.1f;
private static final float HIDE_ADD_BUTTON_THRESHOLD = 0.3f;
private static final float SHOW_ADD_BUTTON_THRESHOLD = 0.5f;
public BottomSheetChromeBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSheetScrolled(
CoordinatorLayout parent, ViewGroup layout, SheetSlideMetrics metrics) {
View scrim = layout.findViewById(R.id.bottom_sheet_bottom_inset_scrim);
View addRecordButton = layout.findViewById(R.id.add_record_btn);
ViewGroup toolbarWrapper = layout.findViewById(R.id.toolbar_wrapper);
ViewGroup toolbar = toolbarWrapper.findViewById(R.id.toolbar);
ViewGroup toolbarTitles = toolbarWrapper.findViewById(R.id.toolbar_titles_layout);
metrics.showWithSheet(scrim, HIDE_SCRIM_THRESHOLD, SHOW_SCRIM_THRESHOLD);
metrics.showWithSheet(addRecordButton, HIDE_ADD_BUTTON_THRESHOLD, SHOW_ADD_BUTTON_THRESHOLD);
toolbarWrapper.setBackgroundColor(layout.getResources().getColor(R.color.colorPrimary));
toolbarWrapper.setTranslationY(
scale(metrics.getVisibleRatio(), 0.3f, 0.5f, -toolbarWrapper.getHeight(), 0));
metrics.showWithSheet(toolbarWrapper.getBackground(), 0.9f, 1);
// Fade in toolbar text labels with sheet expansion.
float alpha = scale(metrics.getTop(), 0, toolbarWrapper.getHeight(), 1f, 0f);
toolbarTitles.setAlpha(alpha);
Log.e("!!!", "" + alpha + " h: " + toolbarWrapper.getHeight() + " t: " + metrics.getTop());
}
}
| Remove debug log statement.
Change-Id: I2851823a3db985553e47e635e241e10549ca4ed5
| gnd/src/main/java/com/google/android/gnd/ui/BottomSheetChromeBehavior.java | Remove debug log statement. | <ide><path>nd/src/main/java/com/google/android/gnd/ui/BottomSheetChromeBehavior.java
<ide> import android.content.Context;
<ide> import android.support.design.widget.CoordinatorLayout;
<ide> import android.util.AttributeSet;
<del>import android.util.Log;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import com.google.android.gnd.R;
<ide> // Fade in toolbar text labels with sheet expansion.
<ide> float alpha = scale(metrics.getTop(), 0, toolbarWrapper.getHeight(), 1f, 0f);
<ide> toolbarTitles.setAlpha(alpha);
<del> Log.e("!!!", "" + alpha + " h: " + toolbarWrapper.getHeight() + " t: " + metrics.getTop());
<ide> }
<ide> } |
|
Java | epl-1.0 | 8170de81a99e4f02ca29c8048bfa0fc45ccc39f4 | 0 | debrief/debrief,theanuradha/debrief,pecko/debrief,alastrina123/debrief,theanuradha/debrief,theanuradha/debrief,alastrina123/debrief,alastrina123/debrief,debrief/debrief,debrief/debrief,pecko/debrief,theanuradha/debrief,theanuradha/debrief,pecko/debrief,debrief/debrief,theanuradha/debrief,pecko/debrief,alastrina123/debrief,pecko/debrief,pecko/debrief,alastrina123/debrief,pecko/debrief,alastrina123/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,alastrina123/debrief | package org.mwc.cmap.gt2plot.views;
import java.util.Random;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SampleView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "org.mwc.cmap.gt2plot.views.SampleView";
private Action action1;
/**
* The constructor.
*/
public SampleView() {
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
public void createPartControl(Composite parent) {
Canvas myCanvas = new Canvas(parent, SWT.NONE);
myCanvas.addPaintListener(new PaintListener(){
public void paintControl(PaintEvent e)
{
Random random = new Random();
int y2 = random.nextInt(100);
e.gc.drawLine(22, 33, 44, y2 );
}});
makeActions();
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(action1);
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(action1);
}
private void makeActions() {
action1 = new Action() {
public void run() {
System.out.println("hello world");
}
};
action1.setText("Action 1");
action1.setToolTipText("Action 1 tooltip");
action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
}
} | trunk/org.mwc.cmap.gt2Plot/src/org/mwc/cmap/gt2plot/views/SampleView.java | package org.mwc.cmap.gt2plot.views;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SampleView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "org.mwc.cmap.gt2plot.views.SampleView";
private TableViewer viewer;
private Action action1;
private Action action2;
private Action doubleClickAction;
/*
* The content provider class is responsible for
* providing objects to the view. It can wrap
* existing objects in adapters or simply return
* objects as-is. These objects may be sensitive
* to the current input of the view, or ignore
* it and always show the same content
* (like Task List, for example).
*/
class ViewContentProvider implements IStructuredContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
return new String[] { "One", "Two", "Three" };
}
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().
getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
class NameSorter extends ViewerSorter {
}
/**
* The constructor.
*/
public SampleView() {
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(getViewSite());
makeActions();
hookContextMenu();
hookDoubleClickAction();
contributeToActionBars();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
SampleView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(action1);
manager.add(new Separator());
manager.add(action2);
}
private void fillContextMenu(IMenuManager manager) {
manager.add(action1);
manager.add(action2);
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(action1);
manager.add(action2);
}
private void makeActions() {
action1 = new Action() {
public void run() {
showMessage("Action 1 executed");
}
};
action1.setText("Action 1");
action1.setToolTipText("Action 1 tooltip");
action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
action2 = new Action() {
public void run() {
showMessage("Action 2 executed");
}
};
action2.setText("Action 2");
action2.setToolTipText("Action 2 tooltip");
action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
doubleClickAction = new Action() {
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection)selection).getFirstElement();
showMessage("Double-click detected on "+obj.toString());
}
};
}
private void hookDoubleClickAction() {
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
doubleClickAction.run();
}
});
}
private void showMessage(String message) {
MessageDialog.openInformation(
viewer.getControl().getShell(),
"Sample View",
message);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
viewer.getControl().setFocus();
}
} | reduce to minimum functionality
git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@3349 cb33b658-6c9e-41a7-9690-cba343611204
| trunk/org.mwc.cmap.gt2Plot/src/org/mwc/cmap/gt2plot/views/SampleView.java | reduce to minimum functionality | <ide><path>runk/org.mwc.cmap.gt2Plot/src/org/mwc/cmap/gt2plot/views/SampleView.java
<ide> package org.mwc.cmap.gt2plot.views;
<ide>
<ide>
<add>import java.util.Random;
<add>
<add>import org.eclipse.jface.action.Action;
<add>import org.eclipse.jface.action.IMenuManager;
<add>import org.eclipse.jface.action.IToolBarManager;
<add>import org.eclipse.swt.SWT;
<add>import org.eclipse.swt.events.PaintEvent;
<add>import org.eclipse.swt.events.PaintListener;
<add>import org.eclipse.swt.widgets.Canvas;
<ide> import org.eclipse.swt.widgets.Composite;
<del>import org.eclipse.ui.part.*;
<del>import org.eclipse.jface.viewers.*;
<del>import org.eclipse.swt.graphics.Image;
<del>import org.eclipse.jface.action.*;
<del>import org.eclipse.jface.dialogs.MessageDialog;
<del>import org.eclipse.ui.*;
<del>import org.eclipse.swt.widgets.Menu;
<del>import org.eclipse.swt.SWT;
<add>import org.eclipse.ui.IActionBars;
<add>import org.eclipse.ui.ISharedImages;
<add>import org.eclipse.ui.PlatformUI;
<add>import org.eclipse.ui.part.ViewPart;
<ide>
<ide>
<ide> /**
<ide> */
<ide> public static final String ID = "org.mwc.cmap.gt2plot.views.SampleView";
<ide>
<del> private TableViewer viewer;
<ide> private Action action1;
<del> private Action action2;
<del> private Action doubleClickAction;
<del>
<del> /*
<del> * The content provider class is responsible for
<del> * providing objects to the view. It can wrap
<del> * existing objects in adapters or simply return
<del> * objects as-is. These objects may be sensitive
<del> * to the current input of the view, or ignore
<del> * it and always show the same content
<del> * (like Task List, for example).
<del> */
<del>
<del> class ViewContentProvider implements IStructuredContentProvider {
<del> public void inputChanged(Viewer v, Object oldInput, Object newInput) {
<del> }
<del> public void dispose() {
<del> }
<del> public Object[] getElements(Object parent) {
<del> return new String[] { "One", "Two", "Three" };
<del> }
<del> }
<del> class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
<del> public String getColumnText(Object obj, int index) {
<del> return getText(obj);
<del> }
<del> public Image getColumnImage(Object obj, int index) {
<del> return getImage(obj);
<del> }
<del> public Image getImage(Object obj) {
<del> return PlatformUI.getWorkbench().
<del> getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
<del> }
<del> }
<del> class NameSorter extends ViewerSorter {
<del> }
<del>
<ide> /**
<ide> * The constructor.
<ide> */
<ide> * to create the viewer and initialize it.
<ide> */
<ide> public void createPartControl(Composite parent) {
<del> viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
<del> viewer.setContentProvider(new ViewContentProvider());
<del> viewer.setLabelProvider(new ViewLabelProvider());
<del> viewer.setSorter(new NameSorter());
<del> viewer.setInput(getViewSite());
<add> Canvas myCanvas = new Canvas(parent, SWT.NONE);
<add> myCanvas.addPaintListener(new PaintListener(){
<add>
<add> public void paintControl(PaintEvent e)
<add> {
<add> Random random = new Random();
<add> int y2 = random.nextInt(100);
<add> e.gc.drawLine(22, 33, 44, y2 );
<add> }});
<ide> makeActions();
<del> hookContextMenu();
<del> hookDoubleClickAction();
<ide> contributeToActionBars();
<del> }
<del>
<del> private void hookContextMenu() {
<del> MenuManager menuMgr = new MenuManager("#PopupMenu");
<del> menuMgr.setRemoveAllWhenShown(true);
<del> menuMgr.addMenuListener(new IMenuListener() {
<del> public void menuAboutToShow(IMenuManager manager) {
<del> SampleView.this.fillContextMenu(manager);
<del> }
<del> });
<del> Menu menu = menuMgr.createContextMenu(viewer.getControl());
<del> viewer.getControl().setMenu(menu);
<del> getSite().registerContextMenu(menuMgr, viewer);
<ide> }
<ide>
<ide> private void contributeToActionBars() {
<ide>
<ide> private void fillLocalPullDown(IMenuManager manager) {
<ide> manager.add(action1);
<del> manager.add(new Separator());
<del> manager.add(action2);
<ide> }
<ide>
<del> private void fillContextMenu(IMenuManager manager) {
<del> manager.add(action1);
<del> manager.add(action2);
<del> // Other plug-ins can contribute there actions here
<del> manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
<del> }
<del>
<ide> private void fillLocalToolBar(IToolBarManager manager) {
<ide> manager.add(action1);
<del> manager.add(action2);
<ide> }
<ide>
<ide> private void makeActions() {
<ide> action1 = new Action() {
<ide> public void run() {
<del> showMessage("Action 1 executed");
<add> System.out.println("hello world");
<ide> }
<ide> };
<ide> action1.setText("Action 1");
<ide> action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
<ide> getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
<ide>
<del> action2 = new Action() {
<del> public void run() {
<del> showMessage("Action 2 executed");
<del> }
<del> };
<del> action2.setText("Action 2");
<del> action2.setToolTipText("Action 2 tooltip");
<del> action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
<del> getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
<del> doubleClickAction = new Action() {
<del> public void run() {
<del> ISelection selection = viewer.getSelection();
<del> Object obj = ((IStructuredSelection)selection).getFirstElement();
<del> showMessage("Double-click detected on "+obj.toString());
<del> }
<del> };
<del> }
<del>
<del> private void hookDoubleClickAction() {
<del> viewer.addDoubleClickListener(new IDoubleClickListener() {
<del> public void doubleClick(DoubleClickEvent event) {
<del> doubleClickAction.run();
<del> }
<del> });
<del> }
<del> private void showMessage(String message) {
<del> MessageDialog.openInformation(
<del> viewer.getControl().getShell(),
<del> "Sample View",
<del> message);
<ide> }
<ide>
<ide> /**
<ide> * Passing the focus request to the viewer's control.
<ide> */
<ide> public void setFocus() {
<del> viewer.getControl().setFocus();
<ide> }
<ide> } |
|
JavaScript | agpl-3.0 | cb6facff49430a5adcb7e2482562c69d33cae84f | 0 | bram1253/testgame,bram1253/testgame | // === Variables === \\
var objects = new Array();
var platformID = 0; // The ID of the next platform
var platformObjects = document.getElementById("platformObjects");
var keysDown = {
arrow_left: false,
arrow_right: false,
arrow_up: false,
arrow_down: false,
spacebar: false,
key_w: false,
key_a: false,
key_s: false,
key_d: false,
};
// ==== Events ==== \\
keyDown = function(key) {
switch(key.code) {
case "ArrowLeft":
keysDown["arrow_left"] = true;
break;
case "ArrowRight":
keysDown["arrow_right"] = true;
break;
case "ArrowUp":
keysDown["arrow_up"] = true;
break;
case "ArrowDown":
keysDown["arrow_down"] = true;
break;
case "Space":
keysDown["spacebar"] = true;
break;
case "KeyW":
keysDown["key_w"] = true;
break;
case "KeyA":
keysDown["key_a"] = true;
break;
case "KeyS":
keysDown["key_s"] = true;
break;
case "KeyD":
keysDown["key_d"] = true;
break;
}
}
keyUp = function(key) {
switch(key.code) {
case "ArrowLeft":
keysDown["arrow_left"] = false;
break;
case "ArrowRight":
keysDown["arrow_right"] = false;
break;
case "ArrowUp":
keysDown["arrow_up"] = false;
break;
case "ArrowDown":
keysDown["arrow_down"] = false;
break;
case "Space":
keysDown["spacebar"] = false;
break;
case "KeyW":
keysDown["key_w"] = false;
break;
case "KeyA":
keysDown["key_a"] = false;
break;
case "KeyS":
keysDown["key_s"] = false;
break;
case "KeyD":
keysDown["key_d"] = false;
break;
}
}
document.onkeydown = this.keyDown;
document.onkeyup = this.keyUp;
// === Objects ==== \\
function gameObj() {
// Variables
this.gravity = 1000; // The gavity, 1000=default
this.speed = 1; // Speed of the game, 1=default
// Init Variables
this.height = 480;
this.width = 640;
this.color = "White";
this.HTMLObj = document.getElementById("gameFrame");
// Init
this.init = function() {
this.HTMLObj.style["height"] = this.height;
this.HTMLObj.style["width"] = this.width;
this.HTMLObj.style["background-color"] = this.color;
}
}
function playerObj() {
// Variables
this.startingHealth = 100;
this.health = this.startingHealth;
// Init Variables
this.x = 0;
this.y = 0;
this.speed = 200; // How much pixels the player should move per second.
this.force = 0; // gravity
this.jumpForce = 500;
this.height = 40;
this.width = 40;
this.color = "Red";
this.HTMLObj = document.getElementById("player");
// Init
this.init = function() {
this.HTMLObj.style["background-color"] = this.color;
this.HTMLObj.style["height"] = this.height;
this.HTMLObj.style["width"] = this.width;
this.HTMLObj.style["left"] = this.x;
this.HTMLObj.style["top"] = this.y;
}
}
function platformObj() {
this.x = 0;
this.y = 0;
this.height = 20;
this.width = 120;
this.color = "Black";
this.HTMLObj;
this.platformName;
// Make the platform
platformName = "platform_" + platformID;
var insertCode = "<div id=\"" + platformName + "\" class=\"platform\"></div>"
platformObjects.innerHTML = platformObjects.innerHTML + insertCode + "\n";
HTMLObj = document.getElementById(platformName);
objects[platformID] = this; // Add the object in the objects array, each platformID should be unique and start with 0
platformID++;
// End making the platform
this.init = function() {
HTMLObj.style["background-color"] = this.color;
HTMLObj.style["height"] = this.height;
HTMLObj.style["width"] = this.width;
HTMLObj.style["left"] = this.x;
HTMLObj.style["top"] = this.y;
}
}
// === Functions === \\
function collisionCheck(x, y) {
if(y > game.height - player.height) {
y = game.height - player.height;
}
for(i=0; i<objects.length; i++) {
var obj = objects[i];
}
if(x==NaN)x=player.x; // Failsafe
if(y==NaN)y=player.y; // Failsafe
return {x, y};
}
function onGround(x, y) {
if(collisionCheck(x, Math.floor(y)+1).y < Math.floor(player.y)+1) {
return true;
} else {
return false;
}
}
function hittingRoof(x, y) {
if(collisionCheck(x, Math.floor(y)-1).y < Math.floor(player.y)-1) {
return true;
} else {
return false;
}
}
function applyGravity(speed) {
// Still have to add enemies in here (when they are added)!
// Apply the force
player.force += (game.gravity * game.speed)*speed;
// If they are on the ground and there is a downwards force
if(onGround(player.x, player.y) && player.force >= 0) {
player.force = 0;
}
// If they are hitting a roof and there is an upwards force
if(hittingRoof(player.x, player.y) && player.force < 0) {
player.force = 0;
}
// Apple the positioning
var newY = player.y + (player.force * speed * game.speed);
player.y = collisionCheck(player.x, newY).y;
}
function handleJumping(speed) {
if(keysDown.arrow_up || keysDown.spacebar || keysDown.key_w) {
if(collisionCheck(player.x, player.y+1).y < player.y+1) { // If on top of something
player.force = -player.jumpForce;
}
}
}
// === Main ==== \\
var game = new gameObj();
var player = new playerObj();
var tmp_testplatform = new platformObj();
function start() {
game.init();
player.init();
tmp_testplatform.x = 200; // tmp
tmp_testplatform.y = 400; // tmp
tmp_testplatform.init(); // tmp
}
function tick(speed) { // 1speed=1sec 0.5speed=2sec 4speed=0.25sec
applyGravity(speed);
// Input / Output -- temporary until gravity has been added
if(keysDown.arrow_right || keysDown.key_d) {
player.x = collisionCheck(player.x + (player.speed * speed * game.speed), player.y).x;
}
if(keysDown.arrow_left || keysDown.key_a) {
player.x = collisionCheck(player.x - (player.speed * speed * game.speed), player.y).x;
}
handleJumping(speed);
// Rendering
player.init();
// Temporary test platform
tmp_testplatform.init();
}
// === Run the game === \\
start();
// This chunk of code will calculate how long it took the previous tick() to take and pass it in the current one. tick(nextSpeed)
var nextSpeed = 0;
var startDate = new Date();
var startTime = startDate.getMilliseconds();
setInterval(function() {
tick(nextSpeed);
var endDate = new Date();
var endTime = endDate.getMilliseconds();
var timeTaken;
if(startTime > endTime) { // In case startTime=998 and endTime=4 or a similar case
timeTaken = (endTime + 1000) - startTime;
} else {
timeTaken = endTime - startTime;
}
//console.log(1000 / timeTaken);
nextSpeed = timeTaken / 1000;
startDate = new Date();
startTime = startDate.getMilliseconds();
}, 1) | site/onload.js | // === Variables === \\
var objects = new Array();
var platformID = 0; // The ID of the next platform
var platformObjects = document.getElementById("platformObjects");
var keysDown = {
arrow_left: false,
arrow_right: false,
arrow_up: false,
arrow_down: false,
spacebar: false,
key_w: false,
key_a: false,
key_s: false,
key_d: false,
};
// ==== Events ==== \\
keyDown = function(key) {
switch(key.code) {
case "ArrowLeft":
keysDown["arrow_left"] = true;
break;
case "ArrowRight":
keysDown["arrow_right"] = true;
break;
case "ArrowUp":
keysDown["arrow_up"] = true;
break;
case "ArrowDown":
keysDown["arrow_down"] = true;
break;
case "Space":
keysDown["spacebar"] = true;
break;
case "KeyW":
keysDown["key_w"] = true;
break;
case "KeyA":
keysDown["key_a"] = true;
break;
case "KeyS":
keysDown["key_s"] = true;
break;
case "KeyD":
keysDown["key_d"] = true;
break;
}
}
keyUp = function(key) {
switch(key.code) {
case "ArrowLeft":
keysDown["arrow_left"] = false;
break;
case "ArrowRight":
keysDown["arrow_right"] = false;
break;
case "ArrowUp":
keysDown["arrow_up"] = false;
break;
case "ArrowDown":
keysDown["arrow_down"] = false;
break;
case "Space":
keysDown["spacebar"] = false;
break;
case "KeyW":
keysDown["key_w"] = false;
break;
case "KeyA":
keysDown["key_a"] = false;
break;
case "KeyS":
keysDown["key_s"] = false;
break;
case "KeyD":
keysDown["key_d"] = false;
break;
}
}
document.onkeydown = this.keyDown;
document.onkeyup = this.keyUp;
// === Objects ==== \\
function gameObj() {
// Variables
this.gravity = 1000; // The gavity, 1000=default
this.speed = 1; // Speed of the game, 1=default
// Init Variables
this.height = 480;
this.width = 640;
this.color = "White";
this.HTMLObj = document.getElementById("gameFrame");
// Init
this.init = function() {
this.HTMLObj.style["height"] = this.height;
this.HTMLObj.style["width"] = this.width;
this.HTMLObj.style["background-color"] = this.color;
}
}
function playerObj() {
// Variables
this.startingHealth = 100;
this.health = this.startingHealth;
// Init Variables
this.x = 0;
this.y = 0;
this.speed = 200; // How much pixels the player should move per second.
this.force = 0; // gravity
this.jumpForce = 500;
this.height = 40;
this.width = 40;
this.color = "Red";
this.HTMLObj = document.getElementById("player");
// Init
this.init = function() {
this.HTMLObj.style["background-color"] = this.color;
this.HTMLObj.style["height"] = this.height;
this.HTMLObj.style["width"] = this.width;
this.HTMLObj.style["left"] = this.x;
this.HTMLObj.style["top"] = this.y;
}
}
function platformObj() {
this.x = 0;
this.y = 0;
this.height = 20;
this.width = 120;
this.color = "Black";
this.HTMLObj;
this.platformName;
// Make the platform
platformName = "platform_" + platformID;
var insertCode = "<div id=\"" + platformName + "\" class=\"platform\"></div>"
platformObjects.innerHTML = platformObjects.innerHTML + insertCode + "\n";
HTMLObj = document.getElementById(platformName);
platformID++;
// End making the platform
this.init = function() {
HTMLObj.style["background-color"] = this.color;
HTMLObj.style["height"] = this.height;
HTMLObj.style["width"] = this.width;
HTMLObj.style["left"] = this.x;
HTMLObj.style["top"] = this.y;
}
}
// === Functions === \\
function collisionCheck(x, y) {
if(y > game.height - player.height) {
y = game.height - player.height;
}
if(x==NaN)x=player.x; // Failsafe
if(y==NaN)y=player.y; // Failsafe
return {x, y};
}
function onGround(x, y) {
if(collisionCheck(x, Math.floor(y)+1).y < Math.floor(player.y)+1) {
return true;
} else {
return false;
}
}
function hittingRoof(x, y) {
if(collisionCheck(x, Math.floor(y)-1).y < Math.floor(player.y)-1) {
return true;
} else {
return false;
}
}
function applyGravity(speed) {
// Still have to add enemies in here (when they are added)!
// Apply the force
player.force += (game.gravity * game.speed)*speed;
// If they are on the ground and there is a downwards force
if(onGround(player.x, player.y) && player.force >= 0) {
player.force = 0;
}
// If they are hitting a roof and there is an upwards force
if(hittingRoof(player.x, player.y) && player.force < 0) {
player.force = 0;
}
// Apple the positioning
var newY = player.y + (player.force * speed);
player.y = collisionCheck(player.x, newY).y;
}
function handleJumping(speed) {
if(keysDown.arrow_up || keysDown.spacebar || keysDown.key_w) {
if(collisionCheck(player.x, player.y+1).y < player.y+1) { // If on top of something
player.force = -player.jumpForce;
}
}
}
// === Main ==== \\
var game = new gameObj();
var player = new playerObj();
var tmp_testplatform = new platformObj();
function start() {
game.init();
player.init();
tmp_testplatform.x = 200; // tmp
tmp_testplatform.y = 400; // tmp
tmp_testplatform.init(); // tmp
}
function tick(speed) { // 1speed=1sec 0.5speed=2sec 4speed=0.25sec
applyGravity(speed);
// Input / Output -- temporary until gravity has been added
if(keysDown.arrow_right || keysDown.key_d) {
player.x = collisionCheck(player.x + (player.speed * speed * game.speed), player.y).x;
}
if(keysDown.arrow_left || keysDown.key_a) {
player.x = collisionCheck(player.x - (player.speed * speed * game.speed), player.y).x;
}
handleJumping(speed);
// Rendering
player.init();
// Temporary test platform
tmp_testplatform.init();
}
// === Run the game === \\
start();
// This chunk of code will calculate how long it took the previous tick() to take and pass it in the current one. tick(nextSpeed)
var nextSpeed = 0;
var startDate = new Date();
var startTime = startDate.getMilliseconds();
setInterval(function() {
tick(nextSpeed);
var endDate = new Date();
var endTime = endDate.getMilliseconds();
var timeTaken;
if(startTime > endTime) { // In case startTime=998 and endTime=4 or a similar case
timeTaken = (endTime + 1000) - startTime;
} else {
timeTaken = endTime - startTime;
}
//console.log(1000 / timeTaken);
nextSpeed = timeTaken / 1000;
startDate = new Date();
startTime = startDate.getMilliseconds();
}, 1) | Prepared for adding collision detection & fixed gravity not respecting game speed.
| site/onload.js | Prepared for adding collision detection & fixed gravity not respecting game speed. | <ide><path>ite/onload.js
<ide>
<ide> platformObjects.innerHTML = platformObjects.innerHTML + insertCode + "\n";
<ide> HTMLObj = document.getElementById(platformName);
<del>
<add>
<add> objects[platformID] = this; // Add the object in the objects array, each platformID should be unique and start with 0
<add>
<ide> platformID++;
<ide> // End making the platform
<ide>
<ide> if(y > game.height - player.height) {
<ide> y = game.height - player.height;
<ide> }
<add>
<add> for(i=0; i<objects.length; i++) {
<add> var obj = objects[i];
<add>
<add>
<add> }
<add>
<ide>
<ide> if(x==NaN)x=player.x; // Failsafe
<ide> if(y==NaN)y=player.y; // Failsafe
<ide> }
<ide>
<ide> // Apple the positioning
<del> var newY = player.y + (player.force * speed);
<add> var newY = player.y + (player.force * speed * game.speed);
<ide> player.y = collisionCheck(player.x, newY).y;
<ide> }
<ide> |
|
Java | lgpl-2.1 | bcbafeffa96ee7f61239aee11a031a94bdb82f2e | 0 | viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.davis.calibration;
import static org.bytedeco.javacpp.opencv_core.CV_32FC2;
import static org.bytedeco.javacpp.opencv_core.CV_64FC3;
import static org.bytedeco.javacpp.opencv_core.CV_8U;
import static org.bytedeco.javacpp.opencv_core.CV_8UC3;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_EPS;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_ITER;
import static org.bytedeco.javacpp.opencv_imgproc.CV_GRAY2RGB;
import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.opencv_calib3d;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.MatVector;
import org.bytedeco.javacpp.opencv_core.Size;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.indexer.DoubleBufferIndexer;
import org.bytedeco.javacpp.indexer.DoubleIndexer;
import org.openni.Device;
import org.openni.DeviceInfo;
import org.openni.OpenNI;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.davis.stereo.SimpleDepthCameraViewerApplication;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.TextRendererScale;
/**
* Calibrates a single camera using DAVIS frames and OpenCV calibration methods.
*
* @author Marc Osswald, Tobi Delbruck
*/
@Description("Calibrates a single camera using DAVIS frames and OpenCV calibration methods")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class SingleCameraCalibration extends EventFilter2D implements FrameAnnotater, Observer /* observes this to get informed about our size */ {
private int sx; // set to chip.getSizeX()
private int sy; // chip.getSizeY()
private int lastTimestamp = 0;
private float[] lastFrame = null, outFrame = null;
/**
* Fires property change with this string when new calibration is available
*/
public static final String EVENT_NEW_CALIBRATION = "EVENT_NEW_CALIBRATION";
private SimpleDepthCameraViewerApplication depthViewerThread;
//encapsulated fields
private boolean realtimePatternDetectionEnabled = getBoolean("realtimePatternDetectionEnabled", true);
private boolean cornerSubPixRefinement = getBoolean("cornerSubPixRefinement", true);
private String dirPath = getString("dirPath", System.getProperty("user.dir"));
private int patternWidth = getInt("patternWidth", 9);
private int patternHeight = getInt("patternHeight", 5);
private int rectangleHeightMm = getInt("rectangleHeightMm", 20); //height in mm
private int rectangleWidthMm = getInt("rectangleWidthMm", 20); //width in mm
private boolean showUndistortedFrames = getBoolean("showUndistortedFrames", false);
private boolean undistortDVSevents = getBoolean("undistortDVSevents", false);
private boolean takeImageOnTimestampReset = getBoolean("takeImageOnTimestampReset", false);
private boolean hideStatisticsAndStatus = getBoolean("hideStatisticsAndStatus", false);
private String fileBaseName = "";
//opencv matrices
private Mat corners; // TODO change to OpenCV java, not bytedeco http://docs.opencv.org/2.4/doc/tutorials/introduction/desktop_java/java_dev_intro.html
private MatVector allImagePoints;
private MatVector allObjectPoints;
private Mat cameraMatrix;
private Mat distortionCoefs;
private MatVector rotationVectors;
private MatVector translationVectors;
private Mat imgIn, imgOut;
private short[] undistortedAddressLUT = null; // stores undistortion LUT for event addresses. values are stored by idx = 2 * (y + sy * x);
private boolean isUndistortedAddressLUTgenerated = false;
private float focalLengthPixels = 0;
private float focalLengthMm = 0;
private Point2D.Float principlePoint = null;
private String calibrationString = "Uncalibrated";
private boolean patternFound;
private int imageCounter = 0;
private boolean calibrated = false;
private boolean actionTriggered = false;
private int nAcqFrames = 0;
private int nMaxAcqFrames = 1;
private final ApsFrameExtractor frameExtractor;
private final FilterChain filterChain;
private boolean saved = false;
private boolean textRendererScaleSet = false;
private float textRendererScale = 0.3f;
public SingleCameraCalibration(AEChip chip) {
super(chip);
chip.addObserver(this);
frameExtractor = new ApsFrameExtractor(chip);
filterChain = new FilterChain(chip);
filterChain.add(frameExtractor);
frameExtractor.setExtRender(false);
setEnclosedFilterChain(filterChain);
resetFilter();
setPropertyTooltip("patternHeight", "height of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("patternWidth", "width of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("realtimePatternDetectionEnabled", "width of checkerboard calibration pattern in internal corner intersections");
setPropertyTooltip("rectangleWidthMm", "width of square rectangles of calibration pattern in mm");
setPropertyTooltip("rectangleHeightMm", "height of square rectangles of calibration pattern in mm");
setPropertyTooltip("showUndistortedFrames", "shows the undistorted frame in the ApsFrameExtractor display, if calibration has been completed");
setPropertyTooltip("undistortDVSevents", "applies LUT undistortion to DVS event address if calibration has been completed; events outside AEChip address space are filtered out");
setPropertyTooltip("takeImageOnTimestampReset", "??");
setPropertyTooltip("cornerSubPixRefinement", "refine corner locations to subpixel resolution");
setPropertyTooltip("calibrate", "run the camera calibration on collected frame data and print results to console");
setPropertyTooltip("depthViewer", "shows the depth or color image viewer if a Kinect device is connected via NI2 interface");
setPropertyTooltip("setPath", "sets the folder and basename of saved images");
setPropertyTooltip("saveCalibration", "saves calibration files to a selected folder");
setPropertyTooltip("loadCalibration", "loads saved calibration files from selected folder");
setPropertyTooltip("clearCalibration", "clears existing calibration");
setPropertyTooltip("takeImage", "snaps a calibration image that forms part of the calibration dataset");
setPropertyTooltip("hideStatisticsAndStatus", "hides the status text");
loadCalibration();
}
/**
* filters in to out. if filtering is enabled, the number of out may be less
* than the number putString in
*
* @param in input events can be null or empty.
* @return the processed events, may be fewer in number. filtering may occur
* in place in the in packet.
*/
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
getEnclosedFilterChain().filterPacket(in);
// for each event only keep it if it is within dt of the last time
// an event happened in the direct neighborhood
Iterator itr = ((ApsDvsEventPacket) in).fullIterator();
while (itr.hasNext()) {
Object o = itr.next();
if (o == null) {
break; // this can occur if we are supplied packet that has data (eIn.g. APS samples) but no events
}
BasicEvent e = (BasicEvent) o;
// if (e.isSpecial()) {
// continue;
// }
//trigger action (on ts reset)
if ((e.timestamp < lastTimestamp) && (e.timestamp < 100000) && takeImageOnTimestampReset) {
log.info("timestamp reset action trigggered");
actionTriggered = true;
nAcqFrames = 0;
}
//acquire new frame
if (frameExtractor.hasNewFrame()) {
lastFrame = frameExtractor.getNewFrame();
//process frame
if (realtimePatternDetectionEnabled) {
patternFound = findCurrentCorners(false);
}
//iterate
if (actionTriggered && (nAcqFrames < nMaxAcqFrames)) {
nAcqFrames++;
generateCalibrationString();
}
//take action
if (actionTriggered && (nAcqFrames == nMaxAcqFrames)) {
patternFound = findCurrentCorners(true);
//reset action
actionTriggered = false;
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
float[] outFrame = undistortFrame(lastFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
frameExtractor.setExtRender(true); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("lens correction enabled");
} else {
frameExtractor.setExtRender(false); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("raw input image");
}
}
//store last timestamp
lastTimestamp = e.timestamp;
if (calibrated && undistortDVSevents && ((ApsDvsEvent) e).isDVSEvent()) {
undistortEvent(e);
}
}
return in;
}
/**
* Undistorts an image frame using the calibration.
*
* @param src the source image, RGB float valued in 0-1 range
* @return float[] destination. IAn internal float[] is created and reused.
* If there is no calibration, the src array is returned.
*/
public float[] undistortFrame(float[] src) {
if (!calibrated) {
return src;
}
FloatPointer ip = new FloatPointer(src);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
Mat img = input.reshape(0, sy);
Mat undistortedImg = new Mat();
opencv_imgproc.undistort(img, undistortedImg, cameraMatrix, distortionCoefs);
Mat imgOut8u = new Mat(sy, sx, CV_8UC3);
cvtColor(undistortedImg, imgOut8u, CV_GRAY2RGB);
Mat outImgF = new Mat(sy, sx, opencv_core.CV_32F);
imgOut8u.convertTo(outImgF, opencv_core.CV_32F, 1.0 / 255, 0);
if (outFrame == null) {
outFrame = new float[sy * sx * 3];
}
outImgF.getFloatBuffer().get(outFrame);
return outFrame;
}
public boolean findCurrentCorners(boolean drawAndSave) {
Size patternSize = new Size(patternWidth, patternHeight);
corners = new Mat();
FloatPointer ip = new FloatPointer(lastFrame);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
imgIn = input.reshape(0, sy);
imgOut = new Mat(sy, sx, CV_8UC3);
cvtColor(imgIn, imgOut, CV_GRAY2RGB);
//opencv_highgui.imshow("test", imgIn);
//opencv_highgui.waitKey(1);
boolean locPatternFound;
try {
locPatternFound = opencv_calib3d.findChessboardCorners(imgIn, patternSize, corners);
} catch (RuntimeException e) {
log.warning(e.toString());
return false;
}
if (drawAndSave) {
//render frame
if (locPatternFound && cornerSubPixRefinement) {
opencv_core.TermCriteria tc = new opencv_core.TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1);
opencv_imgproc.cornerSubPix(imgIn, corners, new Size(3, 3), new Size(-1, -1), tc);
}
opencv_calib3d.drawChessboardCorners(imgOut, patternSize, corners, locPatternFound);
Mat outImgF = new Mat(sy, sx, CV_64FC3);
imgOut.convertTo(outImgF, CV_64FC3, 1.0 / 255, 0);
float[] outFrame = new float[sy * sx * 3];
outImgF.getFloatBuffer().get(outFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
//save image
if (locPatternFound) {
Mat imgSave = new Mat(sy, sx, CV_8U);
opencv_core.flip(imgIn, imgSave, 0);
String filename = chip.getName() + "-" + fileBaseName + "-" + String.format("%03d", imageCounter) + ".jpg";
String fullFilePath = dirPath + "\\" + filename;
org.bytedeco.javacpp.opencv_imgcodecs.imwrite(fullFilePath, imgSave);
log.info("wrote " + fullFilePath);
//save depth sensor image if enabled
if (depthViewerThread != null) {
if (depthViewerThread.isFrameCaptureRunning()) {
//save img
String fileSuffix = "-" + String.format("%03d", imageCounter) + ".jpg";
depthViewerThread.saveLastImage(dirPath, fileSuffix);
}
}
//store image points
if (imageCounter == 0) {
allImagePoints = new MatVector(100);
allObjectPoints = new MatVector(100);
}
allImagePoints.put(imageCounter, corners);
//create and store object points, which are just coordinates in mm of corners of pattern as we know they are drawn on the
// calibration target
Mat objectPoints = new Mat(corners.rows(), 1, opencv_core.CV_32FC3);
float x, y;
for (int h = 0; h < patternHeight; h++) {
y = h * rectangleHeightMm;
for (int w = 0; w < patternWidth; w++) {
x = w * rectangleWidthMm;
objectPoints.getFloatBuffer().put(3 * ((patternWidth * h) + w), x);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 1, y);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 2, 0); // z=0 for object points
}
}
allObjectPoints.put(imageCounter, objectPoints);
//iterate image counter
log.info(String.format("added corner points from image %d", imageCounter));
imageCounter++;
frameExtractor.apsDisplay.setxLabel(filename);
// //debug
// System.out.println(allImagePoints.toString());
// for (int n = 0; n < imageCounter; n++) {
// System.out.println("n=" + n + " " + allImagePoints.get(n).toString());
// for (int i = 0; i < corners.rows(); i++) {
// System.out.println(allImagePoints.get(n).getFloatBuffer().get(2 * i) + " " + allImagePoints.get(n).getFloatBuffer().get(2 * i + 1)+" | "+allObjectPoints.get(n).getFloatBuffer().get(3 * i) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 1) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 2));
// }
// }
} else {
log.warning("corners not found for this image");
}
}
return locPatternFound;
}
@Override
public void annotate(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if (patternFound && realtimePatternDetectionEnabled) {
int n = corners.rows();
int c = 3;
int w = patternWidth;
int h = patternHeight;
//log.info(corners.toString()+" rows="+n+" cols="+corners.cols());
//draw lines
gl.glLineWidth(2f);
gl.glColor3f(0, 0, 1);
//log.info("width="+w+" height="+h);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < h; i++) {
float y0 = corners.getFloatBuffer().get(2 * w * i);
float y1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 2);
float x0 = corners.getFloatBuffer().get((2 * w * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
for (int i = 0; i < w; i++) {
float y0 = corners.getFloatBuffer().get(2 * i);
float y1 = corners.getFloatBuffer().get(2 * ((w * (h - 1)) + i));
float x0 = corners.getFloatBuffer().get((2 * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * ((w * (h - 1)) + i)) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
gl.glEnd();
//draw corners
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 0);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < n; i++) {
float y = corners.getFloatBuffer().get(2 * i);
float x = corners.getFloatBuffer().get((2 * i) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y, x - c);
gl.glVertex2f(y, x + c);
gl.glVertex2f(y - c, x);
gl.glVertex2f(y + c, x);
}
gl.glEnd();
}
if (principlePoint != null) {
gl.glLineWidth(3f);
gl.glColor3f(0, 1, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(principlePoint.x - 4, principlePoint.y);
gl.glVertex2f(principlePoint.x + 4, principlePoint.y);
gl.glVertex2f(principlePoint.x, principlePoint.y - 4);
gl.glVertex2f(principlePoint.x, principlePoint.y + 4);
gl.glEnd();
}
if (!hideStatisticsAndStatus && calibrationString != null) {
// render once to set the scale using the same TextRenderer
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .15f);
MultilineAnnotationTextRenderer.setColor(Color.green);
MultilineAnnotationTextRenderer.setScale(textRendererScale);
MultilineAnnotationTextRenderer.renderMultilineString(calibrationString);
if (!textRendererScaleSet) {
textRendererScaleSet = true;
String[] lines = calibrationString.split("\n", 0);
int max = 0;
String longestString = null;
for (String s : lines) {
if (s.length() > max) {
max = s.length();
longestString = s;
}
}
textRendererScale = TextRendererScale.draw3dScale(MultilineAnnotationTextRenderer.getRenderer(), longestString, chip.getCanvas().getScale(), chip.getSizeX(), .8f);
}
}
}
@Override
public synchronized final void resetFilter() {
initFilter();
filterChain.reset();
patternFound = false;
imageCounter = 0;
principlePoint = null;
}
@Override
public final void initFilter() {
sx = chip.getSizeX();
sy = chip.getSizeY();
}
/**
* @return the realtimePatternDetectionEnabled
*/
public boolean isRealtimePatternDetectionEnabled() {
return realtimePatternDetectionEnabled;
}
/**
* @param realtimePatternDetectionEnabled the
* realtimePatternDetectionEnabled to set
*/
public void setRealtimePatternDetectionEnabled(boolean realtimePatternDetectionEnabled) {
this.realtimePatternDetectionEnabled = realtimePatternDetectionEnabled;
putBoolean("realtimePatternDetectionEnabled", realtimePatternDetectionEnabled);
}
/**
* @return the cornerSubPixRefinement
*/
public boolean isCornerSubPixRefinement() {
return cornerSubPixRefinement;
}
/**
* @param cornerSubPixRefinement the cornerSubPixRefinement to set
*/
public void setCornerSubPixRefinement(boolean cornerSubPixRefinement) {
this.cornerSubPixRefinement = cornerSubPixRefinement;
}
synchronized public void doSetPath() {
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select");
j.setDialogTitle("Select a folder and base file name for calibration images");
j.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
//imagesDirPath = j.getSelectedFile().getAbsolutePath();
dirPath = j.getCurrentDirectory().getPath();
fileBaseName = j.getSelectedFile().getName();
if (!fileBaseName.isEmpty()) {
fileBaseName = "-" + fileBaseName;
}
log.log(Level.INFO, "Changed images path to {0}", dirPath);
putString("dirPath", dirPath);
}
synchronized public void doCalibrate() {
//init
Size imgSize = new Size(sx, sy);
cameraMatrix = new Mat();
distortionCoefs = new Mat();
rotationVectors = new MatVector();
translationVectors = new MatVector();
allImagePoints.resize(imageCounter);
allObjectPoints.resize(imageCounter); // resize has side effect that lists cannot hold any more data
log.info(String.format("calibrating based on %d images sized %d x %d", allObjectPoints.size(), imgSize.width(), imgSize.height()));
//calibrate
try {
opencv_calib3d.calibrateCamera(allObjectPoints, allImagePoints, imgSize, cameraMatrix, distortionCoefs, rotationVectors, translationVectors);
generateCalibrationString();
log.info("see http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html \n"
+ "\nCamera matrix: " + cameraMatrix.toString() + "\n" + printMatD(cameraMatrix)
+ "\nDistortion coefficients k_1 k_2 p_1 p_2 k_3 ...: " + distortionCoefs.toString() + "\n" + printMatD(distortionCoefs)
+ calibrationString);
} catch (RuntimeException e) {
log.warning("calibration failed with exception " + e + "See https://adventuresandwhathaveyou.wordpress.com/2014/03/14/opencv-error-messages-suck/");
} finally {
allImagePoints.resize(100);
allObjectPoints.resize(100);
}
calibrated = true;
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
}
/**
* Generate a look-up table that maps the entire chip to undistorted
* addresses.
*
* @param sx chip size x
* @param sy chip size y
*/
public void generateUndistortedAddressLUT() {
if (!calibrated) {
return;
}
if ((sx == 0) || (sy == 0)) {
return; // not set yet
}
FloatPointer fp = new FloatPointer(2 * sx * sy);
int idx = 0;
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
fp.put(idx++, x);
fp.put(idx++, y);
}
}
Mat dst = new Mat();
Mat pixelArray = new Mat(1, sx * sy, CV_32FC2, fp); // make wide 2 channel matrix of source event x,y
opencv_imgproc.undistortPoints(pixelArray, dst, getCameraMatrix(), getDistortionCoefs());
isUndistortedAddressLUTgenerated = true;
// get the camera matrix elements (focal lengths and principal point)
DoubleIndexer k = getCameraMatrix().createIndexer();
float fx, fy, cx, cy;
fx = (float) k.get(0, 0);
fy = (float) k.get(1, 1);
cx = (float) k.get(0, 2);
cy = (float) k.get(1, 2);
undistortedAddressLUT = new short[2 * sx * sy];
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
idx = 2 * (y + (sy * x));
undistortedAddressLUT[idx] = (short) Math.round((dst.getFloatBuffer().get(idx) * fx) + cx);
undistortedAddressLUT[idx + 1] = (short) Math.round((dst.getFloatBuffer().get(idx + 1) * fy) + cy);
}
}
}
public boolean isUndistortedAddressLUTgenerated() {
return isUndistortedAddressLUTgenerated;
}
private void generateCalibrationString() {
if ((cameraMatrix == null) || cameraMatrix.isNull() || cameraMatrix.empty()) {
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
calibrated = false;
return;
}
DoubleBufferIndexer cameraMatrixIndexer = cameraMatrix.createIndexer();
focalLengthPixels = (float) (cameraMatrixIndexer.get(0, 0) + cameraMatrixIndexer.get(0, 0)) / 2;
focalLengthMm = chip.getPixelWidthUm() * 1e-3f * focalLengthPixels;
principlePoint = new Point2D.Float((float) cameraMatrixIndexer.get(0, 2), (float) cameraMatrixIndexer.get(1, 2));
StringBuilder sb = new StringBuilder();
if (imageCounter > 0) {
sb.append(String.format("Using %d images", imageCounter));
if (!saved) {
sb.append("; not yet saved\n");
} else {
sb.append("; saved\n");
}
} else {
sb.append(String.format("Path:%s\n", shortenDirPath(dirPath)));
}
sb.append(String.format("focal length avg=%.1f pixels=%.2f mm\nPrincipal point (green cross)=%.1f,%.1f, Chip size/2=%.0f,%.0f\n",
focalLengthPixels, focalLengthMm,
principlePoint.x, principlePoint.y,
(float) chip.getSizeX() / 2, (float) chip.getSizeY() / 2));
calibrationString = sb.toString();
calibrated = true;
textRendererScaleSet=false;
}
private static final String SINGLE_CAMERA_CALIBRATION_UNCALIBRATED = "SingleCameraCalibration: uncalibrated";
public String shortenDirPath(String dirPath) {
String dirComp = dirPath;
if (dirPath.length() > 30) {
int n = dirPath.length();
dirComp = dirPath.substring(0, 10) + "..." + dirPath.substring(n - 20, n);
}
return dirComp;
}
synchronized public void doSaveCalibration() {
if (!calibrated) {
JOptionPane.showMessageDialog(null, "No calibration yet");
return;
}
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder to store calibration XML files");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
serializeMat(dirPath, "cameraMatrix", cameraMatrix);
serializeMat(dirPath, "distortionCoefs", distortionCoefs);
saved = true;
generateCalibrationString();
}
static void setButtonState(Container c, String buttonString, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if (buttonString.equals(b.getText())) {
b.setEnabled(flag);
}
} else if (comp instanceof Container) {
setButtonState((Container) comp, buttonString, flag);
}
}
}
synchronized public void doLoadCalibration() {
final JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder that has XML files storing calibration");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
j.setApproveButtonText("Select folder");
j.setApproveButtonToolTipText("Only enabled for a folder that has cameraMatrix.xml and distortionCoefs.xml");
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
j.addPropertyChangeListener(JFileChooser.DIRECTORY_CHANGED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
}
});
int ret = j.showOpenDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
loadCalibration();
}
private boolean calibrationExists(String dirPath) {
String fn = dirPath + File.separator + "cameraMatrix" + ".xml";
File f = new File(fn);
boolean cameraMatrixExists = f.exists();
fn = dirPath + File.separator + "distortionCoefs" + ".xml";
f = new File(fn);
boolean distortionCoefsExists = f.exists();
if (distortionCoefsExists && cameraMatrixExists) {
return true;
} else {
return false;
}
}
synchronized public void doClearCalibration() {
calibrated = false;
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
undistortedAddressLUT = null;
isUndistortedAddressLUTgenerated = false;
}
private void loadCalibration() {
try {
cameraMatrix = deserializeMat(dirPath, "cameraMatrix");
distortionCoefs = deserializeMat(dirPath, "distortionCoefs");
generateCalibrationString();
if (calibrated) {
log.info("Calibrated: loaded cameraMatrix and distortionCoefs from folder " + dirPath);
} else {
log.warning("Uncalibrated: Something was wrong with calibration files so that cameraMatrix or distortionCoefs could not be loaded");
}
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
} catch (Exception i) {
log.warning("Could not load existing calibration from folder " + dirPath + " on construction:" + i.toString());
}
}
/**
* Writes an XML file for the matrix X called path/X.xml
*
* @param dir path to folder
* @param name base name of file
* @param sMat the Mat to write
*/
public void serializeMat(String dir, String name, opencv_core.Mat sMat) {
String fn = dir + File.separator + name + ".xml";
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.WRITE);
opencv_core.write(storage, name, sMat);
storage.release();
log.info("saved in " + fn);
}
public opencv_core.Mat deserializeMat(String dir, String name) {
String fn = dirPath + File.separator + name + ".xml";
opencv_core.Mat mat = new opencv_core.Mat();
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.READ);
opencv_core.read(storage.get(name), mat);
storage.release();
if (mat.empty()) {
return null;
}
return mat;
}
synchronized public void doTakeImage() {
actionTriggered = true;
nAcqFrames = 0;
saved = false;
}
private String printMatD(Mat M) {
StringBuilder sb = new StringBuilder();
int c = 0;
for (int i = 0; i < M.rows(); i++) {
for (int j = 0; j < M.cols(); j++) {
sb.append(String.format("%10.5f\t", M.getDoubleBuffer().get(c)));
c++;
}
sb.append("\n");
}
return sb.toString();
}
/**
* @return the patternWidth
*/
public int getPatternWidth() {
return patternWidth;
}
/**
* @param patternWidth the patternWidth to set
*/
public void setPatternWidth(int patternWidth) {
this.patternWidth = patternWidth;
putInt("patternWidth", patternWidth);
}
/**
* @return the patternHeight
*/
public int getPatternHeight() {
return patternHeight;
}
/**
* @param patternHeight the patternHeight to set
*/
public void setPatternHeight(int patternHeight) {
this.patternHeight = patternHeight;
putInt("patternHeight", patternHeight);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleHeightMm() {
return rectangleHeightMm;
}
/**
* @param rectangleHeightMm the rectangleHeightMm to set
*/
public void setRectangleHeightMm(int rectangleHeightMm) {
this.rectangleHeightMm = rectangleHeightMm;
putInt("rectangleHeightMm", rectangleHeightMm);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleWidthMm() {
return rectangleWidthMm;
}
/**
* @param rectangleWidthMm the rectangleWidthMm to set
*/
public void setRectangleWidthMm(int rectangleWidthMm) {
this.rectangleWidthMm = rectangleWidthMm;
putInt("rectangleWidthMm", rectangleWidthMm);
}
/**
* @return the showUndistortedFrames
*/
public boolean isShowUndistortedFrames() {
return showUndistortedFrames;
}
/**
* @param showUndistortedFrames the showUndistortedFrames to set
*/
public void setShowUndistortedFrames(boolean showUndistortedFrames) {
this.showUndistortedFrames = showUndistortedFrames;
putBoolean("showUndistortedFrames", showUndistortedFrames);
}
/**
* @return the takeImageOnTimestampReset
*/
public boolean isTakeImageOnTimestampReset() {
return takeImageOnTimestampReset;
}
/**
* @param takeImageOnTimestampReset the takeImageOnTimestampReset to set
*/
public void setTakeImageOnTimestampReset(boolean takeImageOnTimestampReset) {
this.takeImageOnTimestampReset = takeImageOnTimestampReset;
putBoolean("takeImageOnTimestampReset", takeImageOnTimestampReset);
}
public void doDepthViewer() {
try {
System.load(System.getProperty("user.dir") + "\\jars\\openni2\\OpenNI2.dll");
// initialize OpenNI
OpenNI.initialize();
List<DeviceInfo> devicesInfo = OpenNI.enumerateDevices();
if (devicesInfo.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Kinect device is connected via NI2 interface", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Device device = Device.open(devicesInfo.get(0).getUri());
depthViewerThread = new SimpleDepthCameraViewerApplication(device);
depthViewerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the camera calibration matrix, as specified in
* <a href="http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html">OpenCV
* camera calibration</a>
* <p>
* The matrix entries can be accessed as shown in code snippet below. Note
* order of matrix entries returned is column-wise; the inner loop is
* vertically over column or y index:
* <pre>
* Mat M;
* for (int i = 0; i < M.rows(); i++) {
* for (int j = 0; j < M.cols(); j++) {
* M.getDoubleBuffer().get(c));
* c++;
* }
* }
* </pre> @return the cameraMatrix
*/
public Mat getCameraMatrix() {
return cameraMatrix;
}
/**
* http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
*
* @return the distortionCoefs
*/
public Mat getDistortionCoefs() {
return distortionCoefs;
}
/**
* Human friendly summary of calibration
*
* @return the calibrationString
*/
public String getCalibrationString() {
return calibrationString;
}
/**
*
* @return true if calibration was completed successfully
*/
public boolean isCalibrated() {
return calibrated;
}
/**
* @return the look-up table of undistorted pixel addresses. The index i is
* obtained by iterating column-wise over the pixel array (y-loop is inner
* loop) until getting to (x,y). Have to multiply by two because both x and
* y addresses are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short[] getUndistortedAddressLUT() {
return undistortedAddressLUT;
}
/**
* @return the undistorted pixel address. The input index i is obtained by
* iterating column-wise over the pixel array (y-loop is inner loop) until
* getting to (x,y). Have to multiply by two because both x and y addresses
* are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short getUndistortedAddressFromLUT(int i) {
return undistortedAddressLUT[i];
}
/**
* Transforms an event to undistorted address, using the LUT computed from
* calibration
*
* @param e input event. The address x and y are modified to the unmodified
* address. If the address falls outside the Chip boundaries, the event is
* filtered out.
* @return true if the transformation succeeds within chip boundaries, false
* if the event has been filtered out.
*/
public boolean undistortEvent(BasicEvent e) {
if (undistortedAddressLUT == null) {
generateUndistortedAddressLUT();
}
int uidx = 2 * (e.y + (sy * e.x));
e.x = getUndistortedAddressFromLUT(uidx);
e.y = getUndistortedAddressFromLUT(uidx + 1);
if (xeob(e.x) || yeob(e.y)) {
e.setFilteredOut(true);
return false;
}
return true;
}
private boolean xeob(int x) {
if ((x < 0) || (x > (sx - 1))) {
return true;
}
return false;
}
private boolean yeob(int y) {
if ((y < 0) || (y > (sy - 1))) {
return true;
}
return false;
}
/**
* @return the undistortDVSevents
*/
public boolean isUndistortDVSevents() {
return undistortDVSevents;
}
/**
* @param undistortDVSevents the undistortDVSevents to set
*/
public void setUndistortDVSevents(boolean undistortDVSevents) {
this.undistortDVSevents = undistortDVSevents;
}
@Override
public void update(Observable o, Object o1) {
if (o instanceof AEChip) {
if (chip.getNumPixels() > 0) {
sx = chip.getSizeX();
sy = chip.getSizeY(); // might not yet have been set in constructor
}
}
}
/**
* @return the hideStatisticsAndStatus
*/
public boolean isHideStatisticsAndStatus() {
return hideStatisticsAndStatus;
}
/**
* @param hideStatisticsAndStatus the hideStatisticsAndStatus to set
*/
public void setHideStatisticsAndStatus(boolean hideStatisticsAndStatus) {
this.hideStatisticsAndStatus = hideStatisticsAndStatus;
putBoolean("hideStatisticsAndStatus", hideStatisticsAndStatus);
}
}
| src/ch/unizh/ini/jaer/projects/davis/calibration/SingleCameraCalibration.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.davis.calibration;
import static org.bytedeco.javacpp.opencv_core.CV_32FC2;
import static org.bytedeco.javacpp.opencv_core.CV_64FC3;
import static org.bytedeco.javacpp.opencv_core.CV_8U;
import static org.bytedeco.javacpp.opencv_core.CV_8UC3;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_EPS;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_ITER;
import static org.bytedeco.javacpp.opencv_imgproc.CV_GRAY2RGB;
import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.opencv_calib3d;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.MatVector;
import org.bytedeco.javacpp.opencv_core.Size;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.indexer.DoubleBufferIndexer;
import org.bytedeco.javacpp.indexer.DoubleIndexer;
import org.openni.Device;
import org.openni.DeviceInfo;
import org.openni.OpenNI;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.davis.stereo.SimpleDepthCameraViewerApplication;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.TextRendererScale;
/**
* Calibrates a single camera using DAVIS frames and OpenCV calibration methods.
*
* @author Marc Osswald, Tobi Delbruck
*/
@Description("Calibrates a single camera using DAVIS frames and OpenCV calibration methods")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class SingleCameraCalibration extends EventFilter2D implements FrameAnnotater, Observer /* observes this to get informed about our size */ {
private int sx; // set to chip.getSizeX()
private int sy; // chip.getSizeY()
private int lastTimestamp = 0;
private float[] lastFrame = null, outFrame = null;
/**
* Fires property change with this string when new calibration is available
*/
public static final String EVENT_NEW_CALIBRATION = "EVENT_NEW_CALIBRATION";
private SimpleDepthCameraViewerApplication depthViewerThread;
//encapsulated fields
private boolean realtimePatternDetectionEnabled = getBoolean("realtimePatternDetectionEnabled", true);
private boolean cornerSubPixRefinement = getBoolean("cornerSubPixRefinement", true);
private String dirPath = getString("dirPath", System.getProperty("user.dir"));
private int patternWidth = getInt("patternWidth", 9);
private int patternHeight = getInt("patternHeight", 5);
private int rectangleHeightMm = getInt("rectangleHeightMm", 20); //height in mm
private int rectangleWidthMm = getInt("rectangleWidthMm", 20); //width in mm
private boolean showUndistortedFrames = getBoolean("showUndistortedFrames", false);
private boolean undistortDVSevents = getBoolean("undistortDVSevents", false);
private boolean takeImageOnTimestampReset = getBoolean("takeImageOnTimestampReset", false);
private String fileBaseName = "";
//opencv matrices
private Mat corners; // TODO change to OpenCV java, not bytedeco http://docs.opencv.org/2.4/doc/tutorials/introduction/desktop_java/java_dev_intro.html
private MatVector allImagePoints;
private MatVector allObjectPoints;
private Mat cameraMatrix;
private Mat distortionCoefs;
private MatVector rotationVectors;
private MatVector translationVectors;
private Mat imgIn, imgOut;
private short[] undistortedAddressLUT = null; // stores undistortion LUT for event addresses. values are stored by idx = 2 * (y + sy * x);
private boolean isUndistortedAddressLUTgenerated = false;
private float focalLengthPixels = 0;
private float focalLengthMm = 0;
private Point2D.Float principlePoint = null;
private String calibrationString = "Uncalibrated";
private boolean patternFound;
private int imageCounter = 0;
private boolean calibrated = false;
private boolean actionTriggered = false;
private int nAcqFrames = 0;
private int nMaxAcqFrames = 1;
private final ApsFrameExtractor frameExtractor;
private final FilterChain filterChain;
private boolean saved = false;
private boolean textRendererScaleSet = false;
private float textRendererScale = 0.3f;
public SingleCameraCalibration(AEChip chip) {
super(chip);
chip.addObserver(this);
frameExtractor = new ApsFrameExtractor(chip);
filterChain = new FilterChain(chip);
filterChain.add(frameExtractor);
frameExtractor.setExtRender(false);
setEnclosedFilterChain(filterChain);
resetFilter();
setPropertyTooltip("patternHeight", "height of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("patternWidth", "width of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("realtimePatternDetectionEnabled", "width of checkerboard calibration pattern in internal corner intersections");
setPropertyTooltip("rectangleWidthMm", "width of square rectangles of calibration pattern in mm");
setPropertyTooltip("rectangleHeightMm", "height of square rectangles of calibration pattern in mm");
setPropertyTooltip("showUndistortedFrames", "shows the undistorted frame in the ApsFrameExtractor display, if calibration has been completed");
setPropertyTooltip("undistortDVSevents", "applies LUT undistortion to DVS event address if calibration has been completed; events outside AEChip address space are filtered out");
setPropertyTooltip("takeImageOnTimestampReset", "??");
setPropertyTooltip("cornerSubPixRefinement", "refine corner locations to subpixel resolution");
setPropertyTooltip("calibrate", "run the camera calibration on collected frame data and print results to console");
setPropertyTooltip("depthViewer", "shows the depth or color image viewer if a Kinect device is connected via NI2 interface");
setPropertyTooltip("setPath", "sets the folder and basename of saved images");
setPropertyTooltip("saveCalibration", "saves calibration files to a selected folder");
setPropertyTooltip("loadCalibration", "loads saved calibration files from selected folder");
setPropertyTooltip("clearCalibration", "clears existing calibration");
setPropertyTooltip("takeImage", "snaps a calibration image that forms part of the calibration dataset");
loadCalibration();
}
/**
* filters in to out. if filtering is enabled, the number of out may be less
* than the number putString in
*
* @param in input events can be null or empty.
* @return the processed events, may be fewer in number. filtering may occur
* in place in the in packet.
*/
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
getEnclosedFilterChain().filterPacket(in);
// for each event only keep it if it is within dt of the last time
// an event happened in the direct neighborhood
Iterator itr = ((ApsDvsEventPacket) in).fullIterator();
while (itr.hasNext()) {
Object o = itr.next();
if (o == null) {
break; // this can occur if we are supplied packet that has data (eIn.g. APS samples) but no events
}
BasicEvent e = (BasicEvent) o;
// if (e.isSpecial()) {
// continue;
// }
//trigger action (on ts reset)
if ((e.timestamp < lastTimestamp) && (e.timestamp < 100000) && takeImageOnTimestampReset) {
log.info("timestamp reset action trigggered");
actionTriggered = true;
nAcqFrames = 0;
}
//acquire new frame
if (frameExtractor.hasNewFrame()) {
lastFrame = frameExtractor.getNewFrame();
//process frame
if (realtimePatternDetectionEnabled) {
patternFound = findCurrentCorners(false);
}
//iterate
if (actionTriggered && (nAcqFrames < nMaxAcqFrames)) {
nAcqFrames++;
generateCalibrationString();
}
//take action
if (actionTriggered && (nAcqFrames == nMaxAcqFrames)) {
patternFound = findCurrentCorners(true);
//reset action
actionTriggered = false;
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
float[] outFrame = undistortFrame(lastFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
frameExtractor.setExtRender(true); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("lens correction enabled");
} else {
frameExtractor.setExtRender(false); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("raw input image");
}
}
//store last timestamp
lastTimestamp = e.timestamp;
if (calibrated && undistortDVSevents && ((ApsDvsEvent) e).isDVSEvent()) {
undistortEvent(e);
}
}
return in;
}
/**
* Undistorts an image frame using the calibration.
*
* @param src the source image, RGB float valued in 0-1 range
* @return float[] destination. IAn internal float[] is created and reused.
* If there is no calibration, the src array is returned.
*/
public float[] undistortFrame(float[] src) {
if (!calibrated) {
return src;
}
FloatPointer ip = new FloatPointer(src);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
Mat img = input.reshape(0, sy);
Mat undistortedImg = new Mat();
opencv_imgproc.undistort(img, undistortedImg, cameraMatrix, distortionCoefs);
Mat imgOut8u = new Mat(sy, sx, CV_8UC3);
cvtColor(undistortedImg, imgOut8u, CV_GRAY2RGB);
Mat outImgF = new Mat(sy, sx, opencv_core.CV_32F);
imgOut8u.convertTo(outImgF, opencv_core.CV_32F, 1.0 / 255, 0);
if (outFrame == null) {
outFrame = new float[sy * sx * 3];
}
outImgF.getFloatBuffer().get(outFrame);
return outFrame;
}
public boolean findCurrentCorners(boolean drawAndSave) {
Size patternSize = new Size(patternWidth, patternHeight);
corners = new Mat();
FloatPointer ip = new FloatPointer(lastFrame);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
imgIn = input.reshape(0, sy);
imgOut = new Mat(sy, sx, CV_8UC3);
cvtColor(imgIn, imgOut, CV_GRAY2RGB);
//opencv_highgui.imshow("test", imgIn);
//opencv_highgui.waitKey(1);
boolean locPatternFound;
try {
locPatternFound = opencv_calib3d.findChessboardCorners(imgIn, patternSize, corners);
} catch (RuntimeException e) {
log.warning(e.toString());
return false;
}
if (drawAndSave) {
//render frame
if (locPatternFound && cornerSubPixRefinement) {
opencv_core.TermCriteria tc = new opencv_core.TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1);
opencv_imgproc.cornerSubPix(imgIn, corners, new Size(3, 3), new Size(-1, -1), tc);
}
opencv_calib3d.drawChessboardCorners(imgOut, patternSize, corners, locPatternFound);
Mat outImgF = new Mat(sy, sx, CV_64FC3);
imgOut.convertTo(outImgF, CV_64FC3, 1.0 / 255, 0);
float[] outFrame = new float[sy * sx * 3];
outImgF.getFloatBuffer().get(outFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
//save image
if (locPatternFound) {
Mat imgSave = new Mat(sy, sx, CV_8U);
opencv_core.flip(imgIn, imgSave, 0);
String filename = chip.getName() + "-" + fileBaseName + "-" + String.format("%03d", imageCounter) + ".jpg";
String fullFilePath = dirPath + "\\" + filename;
org.bytedeco.javacpp.opencv_imgcodecs.imwrite(fullFilePath, imgSave);
log.info("wrote " + fullFilePath);
//save depth sensor image if enabled
if (depthViewerThread != null) {
if (depthViewerThread.isFrameCaptureRunning()) {
//save img
String fileSuffix = "-" + String.format("%03d", imageCounter) + ".jpg";
depthViewerThread.saveLastImage(dirPath, fileSuffix);
}
}
//store image points
if (imageCounter == 0) {
allImagePoints = new MatVector(100);
allObjectPoints = new MatVector(100);
}
allImagePoints.put(imageCounter, corners);
//create and store object points, which are just coordinates in mm of corners of pattern as we know they are drawn on the
// calibration target
Mat objectPoints = new Mat(corners.rows(), 1, opencv_core.CV_32FC3);
float x, y;
for (int h = 0; h < patternHeight; h++) {
y = h * rectangleHeightMm;
for (int w = 0; w < patternWidth; w++) {
x = w * rectangleWidthMm;
objectPoints.getFloatBuffer().put(3 * ((patternWidth * h) + w), x);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 1, y);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 2, 0); // z=0 for object points
}
}
allObjectPoints.put(imageCounter, objectPoints);
//iterate image counter
log.info(String.format("added corner points from image %d", imageCounter));
imageCounter++;
frameExtractor.apsDisplay.setxLabel(filename);
// //debug
// System.out.println(allImagePoints.toString());
// for (int n = 0; n < imageCounter; n++) {
// System.out.println("n=" + n + " " + allImagePoints.get(n).toString());
// for (int i = 0; i < corners.rows(); i++) {
// System.out.println(allImagePoints.get(n).getFloatBuffer().get(2 * i) + " " + allImagePoints.get(n).getFloatBuffer().get(2 * i + 1)+" | "+allObjectPoints.get(n).getFloatBuffer().get(3 * i) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 1) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 2));
// }
// }
} else {
log.warning("corners not found for this image");
}
}
return locPatternFound;
}
@Override
public void annotate(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if (patternFound && realtimePatternDetectionEnabled) {
int n = corners.rows();
int c = 3;
int w = patternWidth;
int h = patternHeight;
//log.info(corners.toString()+" rows="+n+" cols="+corners.cols());
//draw lines
gl.glLineWidth(2f);
gl.glColor3f(0, 0, 1);
//log.info("width="+w+" height="+h);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < h; i++) {
float y0 = corners.getFloatBuffer().get(2 * w * i);
float y1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 2);
float x0 = corners.getFloatBuffer().get((2 * w * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
for (int i = 0; i < w; i++) {
float y0 = corners.getFloatBuffer().get(2 * i);
float y1 = corners.getFloatBuffer().get(2 * ((w * (h - 1)) + i));
float x0 = corners.getFloatBuffer().get((2 * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * ((w * (h - 1)) + i)) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
gl.glEnd();
//draw corners
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 0);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < n; i++) {
float y = corners.getFloatBuffer().get(2 * i);
float x = corners.getFloatBuffer().get((2 * i) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y, x - c);
gl.glVertex2f(y, x + c);
gl.glVertex2f(y - c, x);
gl.glVertex2f(y + c, x);
}
gl.glEnd();
}
if (principlePoint != null) {
gl.glLineWidth(3f);
gl.glColor3f(0, 1, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(principlePoint.x - 4, principlePoint.y);
gl.glVertex2f(principlePoint.x + 4, principlePoint.y);
gl.glVertex2f(principlePoint.x, principlePoint.y - 4);
gl.glVertex2f(principlePoint.x, principlePoint.y + 4);
gl.glEnd();
}
if (calibrationString != null) {
// render once to set the scale using the same TextRenderer
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .15f);
MultilineAnnotationTextRenderer.setColor(Color.green);
MultilineAnnotationTextRenderer.setScale(textRendererScale);
MultilineAnnotationTextRenderer.renderMultilineString(calibrationString);
if (!textRendererScaleSet) {
textRendererScaleSet = true;
String[] lines = calibrationString.split("\n", 0);
int max = 0;
String longestString = null;
for (String s : lines) {
if (s.length() > max) {
max = s.length();
longestString = s;
}
}
textRendererScale = TextRendererScale.draw3dScale(MultilineAnnotationTextRenderer.getRenderer(), longestString, chip.getCanvas().getScale(), chip.getSizeX(), .8f);
}
}
}
@Override
public synchronized final void resetFilter() {
initFilter();
filterChain.reset();
patternFound = false;
imageCounter = 0;
principlePoint = null;
}
@Override
public final void initFilter() {
sx = chip.getSizeX();
sy = chip.getSizeY();
}
/**
* @return the realtimePatternDetectionEnabled
*/
public boolean isRealtimePatternDetectionEnabled() {
return realtimePatternDetectionEnabled;
}
/**
* @param realtimePatternDetectionEnabled the
* realtimePatternDetectionEnabled to set
*/
public void setRealtimePatternDetectionEnabled(boolean realtimePatternDetectionEnabled) {
this.realtimePatternDetectionEnabled = realtimePatternDetectionEnabled;
putBoolean("realtimePatternDetectionEnabled", realtimePatternDetectionEnabled);
}
/**
* @return the cornerSubPixRefinement
*/
public boolean isCornerSubPixRefinement() {
return cornerSubPixRefinement;
}
/**
* @param cornerSubPixRefinement the cornerSubPixRefinement to set
*/
public void setCornerSubPixRefinement(boolean cornerSubPixRefinement) {
this.cornerSubPixRefinement = cornerSubPixRefinement;
}
synchronized public void doSetPath() {
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select");
j.setDialogTitle("Select a folder and base file name for calibration images");
j.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
//imagesDirPath = j.getSelectedFile().getAbsolutePath();
dirPath = j.getCurrentDirectory().getPath();
fileBaseName = j.getSelectedFile().getName();
if (!fileBaseName.isEmpty()) {
fileBaseName = "-" + fileBaseName;
}
log.log(Level.INFO, "Changed images path to {0}", dirPath);
putString("dirPath", dirPath);
}
synchronized public void doCalibrate() {
//init
Size imgSize = new Size(sx, sy);
cameraMatrix = new Mat();
distortionCoefs = new Mat();
rotationVectors = new MatVector();
translationVectors = new MatVector();
allImagePoints.resize(imageCounter);
allObjectPoints.resize(imageCounter); // resize has side effect that lists cannot hold any more data
log.info(String.format("calibrating based on %d images sized %d x %d", allObjectPoints.size(), imgSize.width(), imgSize.height()));
//calibrate
try {
opencv_calib3d.calibrateCamera(allObjectPoints, allImagePoints, imgSize, cameraMatrix, distortionCoefs, rotationVectors, translationVectors);
generateCalibrationString();
log.info("see http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html \n"
+ "\nCamera matrix: " + cameraMatrix.toString() + "\n" + printMatD(cameraMatrix)
+ "\nDistortion coefficients k_1 k_2 p_1 p_2 k_3 ...: " + distortionCoefs.toString() + "\n" + printMatD(distortionCoefs)
+ calibrationString);
} catch (RuntimeException e) {
log.warning("calibration failed with exception " + e + "See https://adventuresandwhathaveyou.wordpress.com/2014/03/14/opencv-error-messages-suck/");
} finally {
allImagePoints.resize(100);
allObjectPoints.resize(100);
}
calibrated = true;
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
}
/**
* Generate a look-up table that maps the entire chip to undistorted
* addresses.
*
* @param sx chip size x
* @param sy chip size y
*/
public void generateUndistortedAddressLUT() {
if (!calibrated) {
return;
}
if ((sx == 0) || (sy == 0)) {
return; // not set yet
}
FloatPointer fp = new FloatPointer(2 * sx * sy);
int idx = 0;
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
fp.put(idx++, x);
fp.put(idx++, y);
}
}
Mat dst = new Mat();
Mat pixelArray = new Mat(1, sx * sy, CV_32FC2, fp); // make wide 2 channel matrix of source event x,y
opencv_imgproc.undistortPoints(pixelArray, dst, getCameraMatrix(), getDistortionCoefs());
isUndistortedAddressLUTgenerated = true;
// get the camera matrix elements (focal lengths and principal point)
DoubleIndexer k = getCameraMatrix().createIndexer();
float fx, fy, cx, cy;
fx = (float) k.get(0, 0);
fy = (float) k.get(1, 1);
cx = (float) k.get(0, 2);
cy = (float) k.get(1, 2);
undistortedAddressLUT = new short[2 * sx * sy];
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
idx = 2 * (y + (sy * x));
undistortedAddressLUT[idx] = (short) Math.round((dst.getFloatBuffer().get(idx) * fx) + cx);
undistortedAddressLUT[idx + 1] = (short) Math.round((dst.getFloatBuffer().get(idx + 1) * fy) + cy);
}
}
}
public boolean isUndistortedAddressLUTgenerated() {
return isUndistortedAddressLUTgenerated;
}
private void generateCalibrationString() {
if ((cameraMatrix == null) || cameraMatrix.isNull() || cameraMatrix.empty()) {
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
calibrated = false;
return;
}
DoubleBufferIndexer cameraMatrixIndexer = cameraMatrix.createIndexer();
focalLengthPixels = (float) (cameraMatrixIndexer.get(0, 0) + cameraMatrixIndexer.get(0, 0)) / 2;
focalLengthMm = chip.getPixelWidthUm() * 1e-3f * focalLengthPixels;
principlePoint = new Point2D.Float((float) cameraMatrixIndexer.get(0, 2), (float) cameraMatrixIndexer.get(1, 2));
StringBuilder sb = new StringBuilder();
if (imageCounter > 0) {
sb.append(String.format("Using %d images", imageCounter));
if (!saved) {
sb.append("; not yet saved\n");
} else {
sb.append("; saved\n");
}
} else {
sb.append(String.format("Path:%s\n", shortenDirPath(dirPath)));
}
sb.append(String.format("focal length avg=%.1f pixels=%.2f mm\nPrincipal point (green cross)=%.1f,%.1f, Chip size/2=%.0f,%.0f\n",
focalLengthPixels, focalLengthMm,
principlePoint.x, principlePoint.y,
(float) chip.getSizeX() / 2, (float) chip.getSizeY() / 2));
calibrationString = sb.toString();
calibrated = true;
textRendererScaleSet=false;
}
private static final String SINGLE_CAMERA_CALIBRATION_UNCALIBRATED = "SingleCameraCalibration: uncalibrated";
public String shortenDirPath(String dirPath) {
String dirComp = dirPath;
if (dirPath.length() > 30) {
int n = dirPath.length();
dirComp = dirPath.substring(0, 10) + "..." + dirPath.substring(n - 20, n);
}
return dirComp;
}
synchronized public void doSaveCalibration() {
if (!calibrated) {
JOptionPane.showMessageDialog(null, "No calibration yet");
return;
}
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder to store calibration XML files");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
serializeMat(dirPath, "cameraMatrix", cameraMatrix);
serializeMat(dirPath, "distortionCoefs", distortionCoefs);
saved = true;
generateCalibrationString();
}
static void setButtonState(Container c, String buttonString, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if (buttonString.equals(b.getText())) {
b.setEnabled(flag);
}
} else if (comp instanceof Container) {
setButtonState((Container) comp, buttonString, flag);
}
}
}
synchronized public void doLoadCalibration() {
final JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder that has XML files storing calibration");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
j.setApproveButtonText("Select folder");
j.setApproveButtonToolTipText("Only enabled for a folder that has cameraMatrix.xml and distortionCoefs.xml");
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
j.addPropertyChangeListener(JFileChooser.DIRECTORY_CHANGED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
}
});
int ret = j.showOpenDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
loadCalibration();
}
private boolean calibrationExists(String dirPath) {
String fn = dirPath + File.separator + "cameraMatrix" + ".xml";
File f = new File(fn);
boolean cameraMatrixExists = f.exists();
fn = dirPath + File.separator + "distortionCoefs" + ".xml";
f = new File(fn);
boolean distortionCoefsExists = f.exists();
if (distortionCoefsExists && cameraMatrixExists) {
return true;
} else {
return false;
}
}
synchronized public void doClearCalibration() {
calibrated = false;
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
undistortedAddressLUT = null;
isUndistortedAddressLUTgenerated = false;
}
private void loadCalibration() {
try {
cameraMatrix = deserializeMat(dirPath, "cameraMatrix");
distortionCoefs = deserializeMat(dirPath, "distortionCoefs");
generateCalibrationString();
if (calibrated) {
log.info("Calibrated: loaded cameraMatrix and distortionCoefs from folder " + dirPath);
} else {
log.warning("Uncalibrated: Something was wrong with calibration files so that cameraMatrix or distortionCoefs could not be loaded");
}
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
} catch (Exception i) {
log.warning("Could not load existing calibration from folder " + dirPath + " on construction:" + i.toString());
}
}
/**
* Writes an XML file for the matrix X called path/X.xml
*
* @param dir path to folder
* @param name base name of file
* @param sMat the Mat to write
*/
public void serializeMat(String dir, String name, opencv_core.Mat sMat) {
String fn = dir + File.separator + name + ".xml";
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.WRITE);
opencv_core.write(storage, name, sMat);
storage.release();
log.info("saved in " + fn);
}
public opencv_core.Mat deserializeMat(String dir, String name) {
String fn = dirPath + File.separator + name + ".xml";
opencv_core.Mat mat = new opencv_core.Mat();
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.READ);
opencv_core.read(storage.get(name), mat);
storage.release();
if (mat.empty()) {
return null;
}
return mat;
}
synchronized public void doTakeImage() {
actionTriggered = true;
nAcqFrames = 0;
saved = false;
}
private String printMatD(Mat M) {
StringBuilder sb = new StringBuilder();
int c = 0;
for (int i = 0; i < M.rows(); i++) {
for (int j = 0; j < M.cols(); j++) {
sb.append(String.format("%10.5f\t", M.getDoubleBuffer().get(c)));
c++;
}
sb.append("\n");
}
return sb.toString();
}
/**
* @return the patternWidth
*/
public int getPatternWidth() {
return patternWidth;
}
/**
* @param patternWidth the patternWidth to set
*/
public void setPatternWidth(int patternWidth) {
this.patternWidth = patternWidth;
putInt("patternWidth", patternWidth);
}
/**
* @return the patternHeight
*/
public int getPatternHeight() {
return patternHeight;
}
/**
* @param patternHeight the patternHeight to set
*/
public void setPatternHeight(int patternHeight) {
this.patternHeight = patternHeight;
putInt("patternHeight", patternHeight);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleHeightMm() {
return rectangleHeightMm;
}
/**
* @param rectangleHeightMm the rectangleHeightMm to set
*/
public void setRectangleHeightMm(int rectangleHeightMm) {
this.rectangleHeightMm = rectangleHeightMm;
putInt("rectangleHeightMm", rectangleHeightMm);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleWidthMm() {
return rectangleWidthMm;
}
/**
* @param rectangleWidthMm the rectangleWidthMm to set
*/
public void setRectangleWidthMm(int rectangleWidthMm) {
this.rectangleWidthMm = rectangleWidthMm;
putInt("rectangleWidthMm", rectangleWidthMm);
}
/**
* @return the showUndistortedFrames
*/
public boolean isShowUndistortedFrames() {
return showUndistortedFrames;
}
/**
* @param showUndistortedFrames the showUndistortedFrames to set
*/
public void setShowUndistortedFrames(boolean showUndistortedFrames) {
this.showUndistortedFrames = showUndistortedFrames;
putBoolean("showUndistortedFrames", showUndistortedFrames);
}
/**
* @return the takeImageOnTimestampReset
*/
public boolean isTakeImageOnTimestampReset() {
return takeImageOnTimestampReset;
}
/**
* @param takeImageOnTimestampReset the takeImageOnTimestampReset to set
*/
public void setTakeImageOnTimestampReset(boolean takeImageOnTimestampReset) {
this.takeImageOnTimestampReset = takeImageOnTimestampReset;
putBoolean("takeImageOnTimestampReset", takeImageOnTimestampReset);
}
public void doDepthViewer() {
try {
System.load(System.getProperty("user.dir") + "\\jars\\openni2\\OpenNI2.dll");
// initialize OpenNI
OpenNI.initialize();
List<DeviceInfo> devicesInfo = OpenNI.enumerateDevices();
if (devicesInfo.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Kinect device is connected via NI2 interface", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Device device = Device.open(devicesInfo.get(0).getUri());
depthViewerThread = new SimpleDepthCameraViewerApplication(device);
depthViewerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the camera calibration matrix, as specified in
* <a href="http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html">OpenCV
* camera calibration</a>
* <p>
* The matrix entries can be accessed as shown in code snippet below. Note
* order of matrix entries returned is column-wise; the inner loop is
* vertically over column or y index:
* <pre>
* Mat M;
* for (int i = 0; i < M.rows(); i++) {
* for (int j = 0; j < M.cols(); j++) {
* M.getDoubleBuffer().get(c));
* c++;
* }
* }
* </pre> @return the cameraMatrix
*/
public Mat getCameraMatrix() {
return cameraMatrix;
}
/**
* http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
*
* @return the distortionCoefs
*/
public Mat getDistortionCoefs() {
return distortionCoefs;
}
/**
* Human friendly summary of calibration
*
* @return the calibrationString
*/
public String getCalibrationString() {
return calibrationString;
}
/**
*
* @return true if calibration was completed successfully
*/
public boolean isCalibrated() {
return calibrated;
}
/**
* @return the look-up table of undistorted pixel addresses. The index i is
* obtained by iterating column-wise over the pixel array (y-loop is inner
* loop) until getting to (x,y). Have to multiply by two because both x and
* y addresses are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short[] getUndistortedAddressLUT() {
return undistortedAddressLUT;
}
/**
* @return the undistorted pixel address. The input index i is obtained by
* iterating column-wise over the pixel array (y-loop is inner loop) until
* getting to (x,y). Have to multiply by two because both x and y addresses
* are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short getUndistortedAddressFromLUT(int i) {
return undistortedAddressLUT[i];
}
/**
* Transforms an event to undistorted address, using the LUT computed from
* calibration
*
* @param e input event. The address x and y are modified to the unmodified
* address. If the address falls outside the Chip boundaries, the event is
* filtered out.
* @return true if the transformation succeeds within chip boundaries, false
* if the event has been filtered out.
*/
public boolean undistortEvent(BasicEvent e) {
if (undistortedAddressLUT == null) {
generateUndistortedAddressLUT();
}
int uidx = 2 * (e.y + (sy * e.x));
e.x = getUndistortedAddressFromLUT(uidx);
e.y = getUndistortedAddressFromLUT(uidx + 1);
if (xeob(e.x) || yeob(e.y)) {
e.setFilteredOut(true);
return false;
}
return true;
}
private boolean xeob(int x) {
if ((x < 0) || (x > (sx - 1))) {
return true;
}
return false;
}
private boolean yeob(int y) {
if ((y < 0) || (y > (sy - 1))) {
return true;
}
return false;
}
/**
* @return the undistortDVSevents
*/
public boolean isUndistortDVSevents() {
return undistortDVSevents;
}
/**
* @param undistortDVSevents the undistortDVSevents to set
*/
public void setUndistortDVSevents(boolean undistortDVSevents) {
this.undistortDVSevents = undistortDVSevents;
}
@Override
public void update(Observable o, Object o1) {
if (o instanceof AEChip) {
if (chip.getNumPixels() > 0) {
sx = chip.getSizeX();
sy = chip.getSizeY(); // might not yet have been set in constructor
}
}
}
}
| added option to SingleCameraCalibration to hide the status text, for publication images
git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@8600 b7f4320f-462c-0410-a916-d9f35bb82d52
| src/ch/unizh/ini/jaer/projects/davis/calibration/SingleCameraCalibration.java | added option to SingleCameraCalibration to hide the status text, for publication images | <ide><path>rc/ch/unizh/ini/jaer/projects/davis/calibration/SingleCameraCalibration.java
<ide> private boolean showUndistortedFrames = getBoolean("showUndistortedFrames", false);
<ide> private boolean undistortDVSevents = getBoolean("undistortDVSevents", false);
<ide> private boolean takeImageOnTimestampReset = getBoolean("takeImageOnTimestampReset", false);
<add> private boolean hideStatisticsAndStatus = getBoolean("hideStatisticsAndStatus", false);
<ide> private String fileBaseName = "";
<ide>
<ide> //opencv matrices
<ide> setPropertyTooltip("loadCalibration", "loads saved calibration files from selected folder");
<ide> setPropertyTooltip("clearCalibration", "clears existing calibration");
<ide> setPropertyTooltip("takeImage", "snaps a calibration image that forms part of the calibration dataset");
<add> setPropertyTooltip("hideStatisticsAndStatus", "hides the status text");
<ide> loadCalibration();
<ide> }
<ide>
<ide>
<ide> }
<ide>
<del> if (calibrationString != null) {
<add> if (!hideStatisticsAndStatus && calibrationString != null) {
<ide> // render once to set the scale using the same TextRenderer
<ide> MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .15f);
<ide> MultilineAnnotationTextRenderer.setColor(Color.green);
<ide> }
<ide> }
<ide>
<add> /**
<add> * @return the hideStatisticsAndStatus
<add> */
<add> public boolean isHideStatisticsAndStatus() {
<add> return hideStatisticsAndStatus;
<add> }
<add>
<add> /**
<add> * @param hideStatisticsAndStatus the hideStatisticsAndStatus to set
<add> */
<add> public void setHideStatisticsAndStatus(boolean hideStatisticsAndStatus) {
<add> this.hideStatisticsAndStatus = hideStatisticsAndStatus;
<add> putBoolean("hideStatisticsAndStatus", hideStatisticsAndStatus);
<add> }
<add>
<ide> } |
|
Java | agpl-3.0 | 40ad0e36f5a53de5c6b137e7c22b0b2318c767eb | 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 | a80959b6-2e60-11e5-9284-b827eb9e62be | hello.java | a803df18-2e60-11e5-9284-b827eb9e62be | a80959b6-2e60-11e5-9284-b827eb9e62be | hello.java | a80959b6-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>a803df18-2e60-11e5-9284-b827eb9e62be
<add>a80959b6-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 51bc78d2f5c6258d6bd5e04aa9e5edb89e16e584 | 0 | paulcwarren/spring-content,paulcwarren/spring-content,paulcwarren/spring-content | package org.springframework.content.solr;
import org.springframework.content.commons.utils.ReflectionService;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.springframework.content.commons.repository.ContentAccessException;
import org.springframework.content.commons.repository.ContentRepositoryExtension;
import org.springframework.content.commons.repository.ContentRepositoryInvoker;
import org.springframework.content.commons.search.Searchable;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
public class SolrSearchImpl implements Searchable<Object>, ContentRepositoryExtension {
private SolrClient solr;
private ReflectionService reflectionService;
private ConversionService conversionService;
private SolrProperties solrProperties;
private String field = "id";
public SolrSearchImpl(SolrClient solr, ReflectionService reflectionService, ConversionService conversionService, SolrProperties solrProperties) {
this.solr = solr;
this.reflectionService = reflectionService;
this.conversionService = conversionService;
this.solrProperties = solrProperties;
}
@Override
public List<Object> findKeyword(String queryStr) {
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAllKeywords(String... terms) {
String queryStr = this.parseTerms("AND", terms);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAnyKeywords(String... terms) {
String queryStr = this.parseTerms("OR", terms);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordsNear(int proximity, String... terms) {
String termStr = this.parseTerms("NONE", terms);
String queryStr = "\""+ termStr + "\"~"+ Integer.toString(proximity);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordStartsWith(String term) {
String queryStr = term + "*";
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordStartsWithAndEndsWith(String a, String b) {
String queryStr = a + "*" + b;
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAllKeywordsWithWeights(String[] terms, double[] weights) {
String queryStr = parseTermsAndWeights("AND", terms, weights);
return getIds(executeQuery(queryStr));
}
/* package */ String parseTermsAndWeights(String operator, String[] terms, double[] weights){
Assert.state(terms.length == weights.length, "all terms must have a weight");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < terms.length - 1; i++){
builder.append("(");
builder.append(terms[i]);
builder.append(")^");
builder.append(weights[i]);
builder.append(" " + operator + " ");
}
builder.append("(");
builder.append(terms[terms.length-1]);
builder.append(")^");
builder.append(weights[weights.length-1]);
return builder.toString();
}
/* package */ String parseTerms(String operator, String... terms){
String separator;
if(operator == "NONE") {
separator = " ";
}
else {
separator = " " + operator + " ";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < terms.length - 1; i++){
builder.append(terms[i]);
builder.append(separator);
}
builder.append(terms[terms.length - 1]);
return builder.toString();
}
/* package */ List<Object> getIds(NamedList response) {
List<Object> ids = new ArrayList<>();
for (int i = 0; i < response.size(); i++) {
SolrDocumentList list = (SolrDocumentList) response.getVal(i);
for (int j = 0; j < list.size(); ++j) {
ids.add(list.get(j).getFieldValue("id"));
}
}
return ids;
}
/* package */ QueryRequest solrAuthenticate(QueryRequest request) {
request.setBasicAuthCredentials(solrProperties.getUser(), solrProperties.getPassword());
return request;
}
/* package */ NamedList<Object> executeQuery(String queryString) {
SolrQuery query = new SolrQuery();
query.setQuery(queryString);
query.setFields(field);
QueryRequest request = new QueryRequest(query);
if (!solrProperties.getUser().isEmpty()) {
request = solrAuthenticate(request);
}
NamedList<Object> response = null;
try {
response = solr.request(request, null);
} catch (SolrServerException e) {
throw new ContentAccessException(String.format("Error running query %s on field %s against solr.", queryString, field), e);
} catch (IOException e) {
throw new ContentAccessException(String.format("Error running query %s on field %s against solr.", queryString, field), e);
}
return response;
}
@Override
public Set<Method> getMethods() {
Set<Method> methods = new HashSet<>();
methods.addAll(Arrays.asList(Searchable.class.getMethods()));
return methods;
}
@Override
public Object invoke(MethodInvocation invocation, ContentRepositoryInvoker invoker) {
List newList = new ArrayList();
Class<? extends Serializable> clazz = invoker.getContentIdClass();
List<String> list = (List) reflectionService.invokeMethod(invocation.getMethod(), this, invocation.getArguments());
for (String item : list) {
if (conversionService.canConvert(item.getClass(), clazz) == false) {
throw new IllegalStateException(String.format("Cannot convert item of type %s to %s", item.getClass().getName(), clazz.getName()));
}
newList.add(conversionService.convert(item, clazz));
}
return newList;
}
}
| spring-content-solr/src/main/java/org/springframework/content/solr/SolrSearchImpl.java | package org.springframework.content.solr;
import org.springframework.content.commons.utils.ReflectionService;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.springframework.content.commons.repository.ContentAccessException;
import org.springframework.content.commons.repository.ContentRepositoryExtension;
import org.springframework.content.commons.repository.ContentRepositoryInvoker;
import org.springframework.content.commons.search.Searchable;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
public class SolrSearchImpl implements Searchable<Object>, ContentRepositoryExtension {
private SolrClient solr;
private ReflectionService reflectionService;
private ConversionService conversionService;
private SolrProperties solrProperties;
private String field = "id";
public SolrSearchImpl(SolrClient solr, ReflectionService reflectionService, ConversionService conversionService, SolrProperties solrProperties) {
this.solr = solr;
this.reflectionService = reflectionService;
this.conversionService = conversionService;
this.solrProperties = solrProperties;
}
@Override
public List<Object> findKeyword(String queryStr) {
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAllKeywords(String... terms) {
String queryStr = this.parseTerms("AND", terms);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAnyKeywords(String... terms) {
String queryStr = this.parseTerms("OR", terms);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordsNear(int proximity, String... terms) {
String termStr = this.parseTerms("NONE", terms);
String queryStr = "\""+ termStr + "\"~"+ Integer.toString(proximity);
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordStartsWith(String term) {
String queryStr = term + "*";
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findKeywordStartsWithAndEndsWith(String a, String b) {
String queryStr = a + "*" + b;
return getIds(executeQuery(queryStr));
}
@Override
public List<Object> findAllKeywordsWithWeights(String[] terms, double[] weights) {
String queryStr = parseTermsAndWeights("AND", terms, weights);
return getIds(executeQuery(queryStr));
}
/* package */ String parseTermsAndWeights(String operator, String[] terms, double[] weights){
Assert.state(terms.length == weights.length, "all terms must have a weight");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < terms.length - 1; i++){
builder.append("(");
builder.append(terms[i]);
builder.append(")^");
builder.append(weights[i]);
builder.append(" " + operator + " ");
}
builder.append("(");
builder.append(terms[terms.length-1]);
builder.append(")^");
builder.append(weights[weights.length-1]);
return builder.toString();
}
/* package */ String parseTerms(String operator, String... terms){
String separator;
if(operator == "NONE") {
separator = " ";
}
else {
separator = " " + operator + " ";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < terms.length - 1; i++){
builder.append(terms[i]);
builder.append(separator);
}
builder.append(terms[terms.length - 1]);
return builder.toString();
}
/* package */ List<Object> getIds(NamedList response) {
List<Object> ids = new ArrayList<>();
for (int i = 1; i < response.size(); i++) {
SolrDocumentList list = (SolrDocumentList) response.getVal(i);
for (int j = 0; j < list.size(); ++j) {
ids.add(list.get(j).getFieldValue("id"));
}
}
return ids;
}
/* package */ QueryRequest solrAuthenticate(QueryRequest request) {
request.setBasicAuthCredentials(solrProperties.getUser(), solrProperties.getPassword());
return request;
}
/* package */ NamedList<Object> executeQuery(String queryString) {
SolrQuery query = new SolrQuery();
query.setQuery(queryString);
query.setFields(field);
QueryRequest request = new QueryRequest(query);
if (!solrProperties.getUser().isEmpty()) {
request = solrAuthenticate(request);
}
NamedList<Object> response = null;
try {
response = solr.request(request, null);
} catch (SolrServerException e) {
throw new ContentAccessException(String.format("Error running query %s on field %s against solr.", queryString, field), e);
} catch (IOException e) {
throw new ContentAccessException(String.format("Error running query %s on field %s against solr.", queryString, field), e);
}
return response;
}
@Override
public Set<Method> getMethods() {
Set<Method> methods = new HashSet<>();
methods.addAll(Arrays.asList(Searchable.class.getMethods()));
return methods;
}
@Override
public Object invoke(MethodInvocation invocation, ContentRepositoryInvoker invoker) {
List newList = new ArrayList();
Class<? extends Serializable> clazz = invoker.getContentIdClass();
List<String> list = (List) reflectionService.invokeMethod(invocation.getMethod(), this, invocation.getArguments());
for (String item : list) {
if (conversionService.canConvert(item.getClass(), clazz) == false) {
throw new IllegalStateException(String.format("Cannot convert item of type %s to %s", item.getClass().getName(), clazz.getName()));
}
newList.add(conversionService.convert(item, clazz));
}
return newList;
}
}
| Fix field array limit issue
| spring-content-solr/src/main/java/org/springframework/content/solr/SolrSearchImpl.java | Fix field array limit issue | <ide><path>pring-content-solr/src/main/java/org/springframework/content/solr/SolrSearchImpl.java
<ide>
<ide> /* package */ List<Object> getIds(NamedList response) {
<ide> List<Object> ids = new ArrayList<>();
<del> for (int i = 1; i < response.size(); i++) {
<add> for (int i = 0; i < response.size(); i++) {
<ide> SolrDocumentList list = (SolrDocumentList) response.getVal(i);
<ide> for (int j = 0; j < list.size(); ++j) {
<ide> ids.add(list.get(j).getFieldValue("id")); |
|
JavaScript | mit | 0af8a6c6eb627e2a04dd01ee3dc0f861ac036bb7 | 0 | IGZjonasdacruz/igz-enterprise-geoshare,IGZjonasdacruz/igz-enterprise-geoshare,IGZjonasdacruz/igz-enterprise-geoshare,IGZjonasdacruz/igz-enterprise-geoshare |
var MongoClient = require('mongodb').MongoClient,
config = require('../util/config').DB,
check = require('validator').check,
logger = require('../util/logger')(__filename);
function DaoBase (options) {
this.collectionName = options.collectionName;
}
DaoBase.prototype.collection = function (callback) {
var self = this;
MongoClient.connect(config.CONN, function (err, db) {
if (err) return callback(err, null);
var collection = db.collection(self.collectionName);
logger.info(self.collectionName + ' collection is open.')
callback(null, db, collection);
});
}
DaoBase.prototype.get = function (id, callback) {
try {
check(id).notNull();
} catch (err) {
return callback(err);
}
this.collection(function (err, db, collection) {
if (err) return callback(err, null);
collection.findOne({_id: id}, function (err, doc) {
if (err) return callback(err, null);
logger.info('Found id="' + id + '" in "' + self.collectionName + '" collection.')
callback(null, doc);
})
});
};
exports.DaoBase = DaoBase;
| src/server/lib/dao/dao_base.js |
var MongoClient = require('mongodb').MongoClient,
config = require('../util/config').DB,
check = require('validator').check;
function DaoBase (options) {
this.collectionName = options.collectionName;
}
DaoBase.prototype.collection = function (callback) {
var self = this;
MongoClient.connect(config.CONN, function (err, db) {
if (err) return callback(err, null);
var collection = db.collection(self.collectionName);
callback(null, db, collection);
});
}
DaoBase.prototype.get = function (id, callback) {
try {
check(id).notNull();
} catch (err) {
return callback(err);
}
this.collection(function (err, db, collection) {
if (err) return callback(err, null);
collection.findOne({_id: id}, function (err, doc) {
if (err) return callback(err, null);
callback(null, doc);
})
});
};
exports.DaoBase = DaoBase;
| Added logger to DaoBase
| src/server/lib/dao/dao_base.js | Added logger to DaoBase | <ide><path>rc/server/lib/dao/dao_base.js
<ide>
<ide> var MongoClient = require('mongodb').MongoClient,
<ide> config = require('../util/config').DB,
<del> check = require('validator').check;
<add> check = require('validator').check,
<add> logger = require('../util/logger')(__filename);
<ide>
<ide> function DaoBase (options) {
<ide> this.collectionName = options.collectionName;
<ide> if (err) return callback(err, null);
<ide>
<ide> var collection = db.collection(self.collectionName);
<add> logger.info(self.collectionName + ' collection is open.')
<add>
<ide> callback(null, db, collection);
<ide> });
<ide> }
<ide>
<ide> collection.findOne({_id: id}, function (err, doc) {
<ide> if (err) return callback(err, null);
<add>
<add> logger.info('Found id="' + id + '" in "' + self.collectionName + '" collection.')
<ide> callback(null, doc);
<ide> })
<ide> }); |
|
JavaScript | mit | 49d4d33f44720e5ceb8b2fb6d813d881bf7c3b0d | 0 | radicaled/whatskdpselectpaying,radicaled/whatskdpselectpaying | window.addEventListener('unhandledrejection', event => {
console.error(event.reason);
});
function numberWithCommas(x) {
if (!x) return;
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
const database = fetch('/kenpc.json')
.then(function(response) {
return response.json()
}).catch(function(ex) {
console.log('parsing failed', ex)
});
Vue.filter('date', value => moment(new Date(value)).format('MMMM YYYY'));
Vue.filter('number', value => numberWithCommas(value));
const KdpSelectChart = Vue.extend({
template: `
<div></div>
`,
props: ["database"],
data: () => ({
}),
ready() {
google.charts.load('current', {'packages':['corechart']});
},
watch: {
'database': function(val, oldVal) {
if (val) {
google.charts.setOnLoadCallback(this.drawChart.bind(this));
}
}
},
methods: {
drawChart() {
if (!this.database) return;
const chartData = [
["Month", "Per Page Payout"]
];
const options = {
vAxis: {
format: 'currency'
}
};
const formatter = new google.visualization.NumberFormat({
prefix: '$',
fractionDigits: 6
});
for(const date of Object.keys(this.database)) {
chartData.push([new Date(date), this.database[date]]);
}
const chart = new google.visualization.LineChart(this.$el);
const data = google.visualization.arrayToDataTable(chartData);
formatter.format(data, 1);
chart.draw(data, options);
}
}
});
const App = Vue.extend({
template: `
<div class='container main-info'>
<h1>What's KDP Select paying these days?</h1>
<h3>{{ lastKnownDate | date}}: \${{ lastKnownValue }}</h3>
<p>How many page reads did you have that month?</p>
<input type="number"
v-model="pageReads"
class="form-control page-reads"
placeholder="A nice, round number" />
<div v-if="pageReads > 0" transition="mad-money">
<h2>
{{pageReads | number}} pages at \${{ lastKnownValue }}...
</h2>
<h3>
You should have made about {{madMonies | currency}}.
</h3>
<p>In the past, you would've made...</p>
<table class='table table-striped table-bordered'>
<thead>
<tr>
<th>Date</th>
<th>Pages</th>
<th>Gross ($)</th>
</tr>
</thead>
<tbody>
<tr v-for="data in pastGross">
<td>{{data.date | date}}</td>
<td>\${{data.perPageAmount}}</td>
<td>{{data.profit | currency}}</td>
</tr>
</tbody>
</table>
</div>
<kdp-select-chart :database="database" />
</div>
`,
components: {
'kdp-select-chart': KdpSelectChart
},
data: () => ({
database: {},
pageReads: null,
pastGross: []
}),
computed: {
lastKnownDate() {
const dates = Object.keys(this.database);
if (dates.length === 0) return;
return dates[dates.length - 1];
},
lastKnownValue() {
const lastKnownDate = this.lastKnownDate
if (!lastKnownDate) return;
return this.database[lastKnownDate];
},
madMonies() {
if (!this.pageReads) return;
if (!this.lastKnownValue) return;
return this.pageReads * this.lastKnownValue;
},
pastGross() {
if (!this.pageReads) return;
const dates = Object.keys(this.database);
const data = [];
for(const date of dates) {
const perPageAmount = this.database[date]
data.push({
date: date,
perPageAmount: perPageAmount,
profit: this.pageReads * perPageAmount
});
}
return data;
}
},
created() {
database.then((database) => {
// Convert date strings to actual date objects.
const formattedData = {};
for(const dateStr of Object.keys(database.dates)) {
const date = new Date(dateStr);
formattedData[date] = database.dates[dateStr];
}
this.database = formattedData;
});
}
});
const mountedApplication = new Vue({
el: '#app',
template: `<div><app /></div>`,
components: {
'app': App
}
})
| src/app.js | window.addEventListener('unhandledrejection', event => {
console.error(event.reason);
});
function numberWithCommas(x) {
if (!x) return;
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
const database = fetch('/kenpc.json')
.then(function(response) {
return response.json()
}).catch(function(ex) {
console.log('parsing failed', ex)
});
Vue.filter('date', value => moment(new Date(value)).format('MMMM YYYY'));
Vue.filter('number', value => numberWithCommas(value));
const KdpSelectChart = Vue.extend({
template: `
<div></div>
`,
props: ["database"],
data: () => ({
}),
ready() {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(this.drawChart.bind(this));
},
methods: {
drawChart() {
if (!this.database) return;
const chartData = [
["Month", "Per Page Payout"]
];
const options = {
vAxis: {
format: 'currency'
}
};
const formatter = new google.visualization.NumberFormat({
prefix: '$',
fractionDigits: 6
});
for(const date of Object.keys(this.database)) {
chartData.push([new Date(date), this.database[date]]);
}
const chart = new google.visualization.LineChart(this.$el);
const data = google.visualization.arrayToDataTable(chartData);
formatter.format(data, 1);
chart.draw(data, options);
}
}
});
const App = Vue.extend({
template: `
<div class='container main-info'>
<h1>What's KDP Select paying these days?</h1>
<h3>{{ lastKnownDate | date}}: \${{ lastKnownValue }}</h3>
<p>How many page reads did you have that month?</p>
<input type="number"
v-model="pageReads"
class="form-control page-reads"
placeholder="A nice, round number" />
<div v-if="pageReads > 0" transition="mad-money">
<h2>
{{pageReads | number}} pages at \${{ lastKnownValue }}...
</h2>
<h3>
You should have made about {{madMonies | currency}}.
</h3>
<p>In the past, you would've made...</p>
<table class='table table-striped table-bordered'>
<thead>
<tr>
<th>Date</th>
<th>Pages</th>
<th>Gross ($)</th>
</tr>
</thead>
<tbody>
<tr v-for="data in pastGross">
<td>{{data.date | date}}</td>
<td>\${{data.perPageAmount}}</td>
<td>{{data.profit | currency}}</td>
</tr>
</tbody>
</table>
</div>
<kdp-select-chart :database="database" />
</div>
`,
components: {
'kdp-select-chart': KdpSelectChart
},
data: () => ({
database: {},
pageReads: null,
pastGross: []
}),
computed: {
lastKnownDate() {
const dates = Object.keys(this.database);
if (dates.length === 0) return;
return dates[dates.length - 1];
},
lastKnownValue() {
const lastKnownDate = this.lastKnownDate
if (!lastKnownDate) return;
return this.database[lastKnownDate];
},
madMonies() {
if (!this.pageReads) return;
if (!this.lastKnownValue) return;
return this.pageReads * this.lastKnownValue;
},
pastGross() {
if (!this.pageReads) return;
const dates = Object.keys(this.database);
const data = [];
for(const date of dates) {
const perPageAmount = this.database[date]
data.push({
date: date,
perPageAmount: perPageAmount,
profit: this.pageReads * perPageAmount
});
}
return data;
}
},
created() {
database.then((database) => {
// Convert date strings to actual date objects.
const formattedData = {};
for(const dateStr of Object.keys(database.dates)) {
const date = new Date(dateStr);
formattedData[date] = database.dates[dateStr];
}
this.database = formattedData;
});
}
});
const mountedApplication = new Vue({
el: '#app',
template: `<div><app /></div>`,
components: {
'app': App
}
})
| only render chart when props data comes in.
| src/app.js | only render chart when props data comes in. | <ide><path>rc/app.js
<ide> }),
<ide> ready() {
<ide> google.charts.load('current', {'packages':['corechart']});
<del> google.charts.setOnLoadCallback(this.drawChart.bind(this));
<add> },
<add> watch: {
<add> 'database': function(val, oldVal) {
<add> if (val) {
<add> google.charts.setOnLoadCallback(this.drawChart.bind(this));
<add> }
<add> }
<ide> },
<ide> methods: {
<ide> drawChart() { |
|
Java | apache-2.0 | 19d28078faa18e28e8e0af815385a2e4865bbd0a | 0 | shils/groovy,eginez/incubator-groovy,ChanJLee/incubator-groovy,avafanasiev/groovy,rlovtangen/groovy-core,nobeans/incubator-groovy,adjohnson916/groovy-core,armsargis/groovy,rlovtangen/groovy-core,rlovtangen/groovy-core,ebourg/groovy-core,aim-for-better/incubator-groovy,guangying945/incubator-groovy,russel/groovy,ebourg/groovy-core,guangying945/incubator-groovy,graemerocher/incubator-groovy,tkruse/incubator-groovy,i55ac/incubator-groovy,taoguan/incubator-groovy,adjohnson916/groovy-core,traneHead/groovy-core,russel/groovy,yukangguo/incubator-groovy,sagarsane/groovy-core,jwagenleitner/incubator-groovy,bsideup/groovy-core,rlovtangen/groovy-core,adjohnson916/groovy-core,pickypg/incubator-groovy,upadhyayap/incubator-groovy,shils/incubator-groovy,mariogarcia/groovy-core,tkruse/incubator-groovy,christoph-frick/groovy-core,traneHead/groovy-core,shils/incubator-groovy,jwagenleitner/groovy,ebourg/groovy-core,adjohnson916/incubator-groovy,gillius/incubator-groovy,paulk-asert/incubator-groovy,fpavageau/groovy,ebourg/incubator-groovy,aaronzirbes/incubator-groovy,genqiang/incubator-groovy,tkruse/incubator-groovy,fpavageau/groovy,alien11689/incubator-groovy,PascalSchumacher/incubator-groovy,PascalSchumacher/incubator-groovy,nkhuyu/incubator-groovy,paplorinc/incubator-groovy,pledbrook/incubator-groovy,upadhyayap/incubator-groovy,kidaa/incubator-groovy,graemerocher/incubator-groovy,bsideup/groovy-core,pledbrook/incubator-groovy,kenzanmedia/incubator-groovy,apache/incubator-groovy,bsideup/incubator-groovy,PascalSchumacher/incubator-groovy,shils/groovy,rabbitcount/incubator-groovy,apache/incubator-groovy,paulk-asert/groovy,antoaravinth/incubator-groovy,alien11689/groovy-core,PascalSchumacher/incubator-groovy,groovy/groovy-core,paulk-asert/incubator-groovy,genqiang/incubator-groovy,adjohnson916/incubator-groovy,paulk-asert/groovy,groovy/groovy-core,bsideup/groovy-core,eginez/incubator-groovy,jwagenleitner/groovy,yukangguo/incubator-groovy,nobeans/incubator-groovy,ChanJLee/incubator-groovy,rlovtangen/groovy-core,bsideup/incubator-groovy,taoguan/incubator-groovy,paplorinc/incubator-groovy,genqiang/incubator-groovy,upadhyayap/incubator-groovy,guangying945/incubator-groovy,eginez/incubator-groovy,paulk-asert/incubator-groovy,EPadronU/incubator-groovy,adjohnson916/groovy-core,alien11689/incubator-groovy,antoaravinth/incubator-groovy,aaronzirbes/incubator-groovy,upadhyayap/incubator-groovy,aim-for-better/incubator-groovy,pickypg/incubator-groovy,avafanasiev/groovy,paulk-asert/incubator-groovy,jwagenleitner/groovy,jwagenleitner/incubator-groovy,i55ac/incubator-groovy,nkhuyu/incubator-groovy,guangying945/incubator-groovy,fpavageau/groovy,mariogarcia/groovy-core,dpolivaev/groovy,russel/groovy,dpolivaev/groovy,russel/incubator-groovy,pickypg/incubator-groovy,russel/incubator-groovy,mariogarcia/groovy-core,gillius/incubator-groovy,ChanJLee/incubator-groovy,fpavageau/groovy,apache/groovy,adjohnson916/incubator-groovy,armsargis/groovy,armsargis/groovy,jwagenleitner/incubator-groovy,christoph-frick/groovy-core,groovy/groovy-core,jwagenleitner/groovy,avafanasiev/groovy,aaronzirbes/incubator-groovy,nobeans/incubator-groovy,apache/groovy,paplorinc/incubator-groovy,nkhuyu/incubator-groovy,mariogarcia/groovy-core,kenzanmedia/incubator-groovy,gillius/incubator-groovy,nobeans/incubator-groovy,sagarsane/incubator-groovy,apache/incubator-groovy,kenzanmedia/incubator-groovy,EPadronU/incubator-groovy,sagarsane/incubator-groovy,shils/groovy,sagarsane/groovy-core,kenzanmedia/incubator-groovy,groovy/groovy-core,antoaravinth/incubator-groovy,avafanasiev/groovy,alien11689/groovy-core,yukangguo/incubator-groovy,nkhuyu/incubator-groovy,paulk-asert/groovy,i55ac/incubator-groovy,rabbitcount/incubator-groovy,russel/groovy,shils/groovy,sagarsane/groovy-core,samanalysis/incubator-groovy,paulk-asert/groovy,kidaa/incubator-groovy,armsargis/groovy,alien11689/groovy-core,samanalysis/incubator-groovy,adjohnson916/groovy-core,apache/incubator-groovy,alien11689/groovy-core,christoph-frick/groovy-core,ChanJLee/incubator-groovy,russel/incubator-groovy,sagarsane/incubator-groovy,PascalSchumacher/incubator-groovy,dpolivaev/groovy,EPadronU/incubator-groovy,rabbitcount/incubator-groovy,alien11689/incubator-groovy,dpolivaev/groovy,traneHead/groovy-core,bsideup/groovy-core,alien11689/incubator-groovy,ebourg/groovy-core,pledbrook/incubator-groovy,sagarsane/groovy-core,christoph-frick/groovy-core,paulk-asert/incubator-groovy,sagarsane/incubator-groovy,sagarsane/groovy-core,ebourg/groovy-core,gillius/incubator-groovy,adjohnson916/incubator-groovy,pickypg/incubator-groovy,ebourg/incubator-groovy,eginez/incubator-groovy,apache/groovy,kidaa/incubator-groovy,antoaravinth/incubator-groovy,russel/incubator-groovy,aim-for-better/incubator-groovy,samanalysis/incubator-groovy,pledbrook/incubator-groovy,samanalysis/incubator-groovy,rabbitcount/incubator-groovy,aaronzirbes/incubator-groovy,genqiang/incubator-groovy,christoph-frick/groovy-core,graemerocher/incubator-groovy,graemerocher/incubator-groovy,ebourg/incubator-groovy,bsideup/incubator-groovy,tkruse/incubator-groovy,kidaa/incubator-groovy,traneHead/groovy-core,ebourg/incubator-groovy,paplorinc/incubator-groovy,jwagenleitner/incubator-groovy,mariogarcia/groovy-core,i55ac/incubator-groovy,shils/incubator-groovy,taoguan/incubator-groovy,apache/groovy,taoguan/incubator-groovy,shils/incubator-groovy,bsideup/incubator-groovy,EPadronU/incubator-groovy,yukangguo/incubator-groovy,groovy/groovy-core,aim-for-better/incubator-groovy,alien11689/groovy-core | /*
* Copyright 2003-2011 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 groovy.util;
import groovy.lang.GroovyRuntimeException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
* <p>A helper class for printing indented text. This can be used stand-alone or, more commonly, from Builders.</p>
*
* <p>By default, a PrintWriter to System.out is used as the Writer, but it is possible
* to change the Writer by passing a new one as a constructor argument.</p>
*
* <p>Indention by default is 2 characters but can be changed by passing a
* different value as a constructor argument.</p>
*
* <p>The following is an example usage. Note that within a "with" block you need to
* specify a parameter name so that this.println is not called instead of IndentPrinter.println: </p>
* <pre>
* new IndentPrinter(new PrintWriter(out)).with { p ->
* p.printIndent()
* p.println('parent1')
* p.incrementIndent()
* p.printIndent()
* p.println('child 1')
* p.printIndent()
* p.println('child 2')
* p.decrementIndent()
* p.printIndent()
* p.println('parent2')
* p.flush()
* }
* </pre>
* <p>The above example prints this to standard output: </p>
* <pre>
* parent1
* child 1
* child 2
* parent2
* </pre>
* @author <a href="mailto:[email protected]">James Strachan</a>
*/
public class IndentPrinter {
private int indentLevel;
private String indent;
private Writer out;
private final boolean addNewlines;
/**
* Creates an IndentPrinter backed by a PrintWriter pointing to System.out, with an indent of two spaces.
*
* @see #IndentPrinter(Writer, String)
*/
public IndentPrinter() {
this(new PrintWriter(System.out), " ");
}
/**
* Creates an IndentPrinter backed by the supplied Writer, with an indent of two spaces.
*
* @param out Writer to output to
* @see #IndentPrinter(Writer, String)
*/
public IndentPrinter(Writer out) {
this(out, " ");
}
/**
* Creates an IndentPrinter backed by the supplied Writer,
* with a user-supplied String to be used for indenting.
*
* @param out Writer to output to
* @param indent character(s) used to indent each line
*/
public IndentPrinter(Writer out, String indent) {
this(out, indent, true);
}
/**
* Creates an IndentPrinter backed by the supplied Writer,
* with a user-supplied String to be used for indenting
* and the ability to override newline handling.
*
* @param out Writer to output to
* @param indent character(s) used to indent each line
* @param addNewlines set to false to gobble all new lines (default true)
*/
public IndentPrinter(Writer out, String indent, boolean addNewlines) {
this.addNewlines = addNewlines;
if (out == null) {
throw new IllegalArgumentException("Must specify a Writer");
}
this.out = out;
this.indent = indent;
}
/**
* Prints a string followed by an end of line character.
*
* @param text String to be written
*/
public void println(String text) {
try {
out.write(text);
println();
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
/**
* Prints a string.
*
* @param text String to be written
*/
public void print(String text) {
try {
out.write(text);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
/**
* Prints a character.
*
* @param c char to be written
*/
public void print(char c) {
try {
out.write(c);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
/**
* Prints the current indent level.
*/
public void printIndent() {
for (int i = 0; i < indentLevel; i++) {
try {
out.write(indent);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
}
/**
* Prints an end-of-line character (if enabled via addNewLines property).
* Defaults to outputting a single '\n' character but by using a custom
* Writer, e.g. PlatformLineWriter, you can get platform-specific
* end-of-line characters.
*
* @see #IndentPrinter(Writer, String, boolean)
*/
public void println() {
if (addNewlines) {
try {
out.write("\n");
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
}
public void incrementIndent() {
++indentLevel;
}
public void decrementIndent() {
--indentLevel;
}
public int getIndentLevel() {
return indentLevel;
}
public void setIndentLevel(int indentLevel) {
this.indentLevel = indentLevel;
}
public void flush() {
try {
out.flush();
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
} | src/main/groovy/util/IndentPrinter.java | /*
* Copyright 2003-2011 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 groovy.util;
import groovy.lang.GroovyRuntimeException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
* <p>A helper class for printing indented text. This can be used stand-alone or, more commonly, from Builders. </p>
*
* <p>By default, a PrintWriter to System.out is used as the Writer, but it is possible
* to change the Writer by passing a new one as a constructor argument. </p>
*
* <p>Indention by default is 2 characters but can be changed by passing a
* different value as a constructor argument. </p>
*
* <p>The following is an example usage. Note that within a "with" block you need to
* specify a parameter name so that this.println is not called instead of IndentPrinter.println: </p>
* <pre>
* new IndentPrinter(new PrintWriter(out)).with { p ->
* p.printIndent()
* p.println('parent1')
* p.incrementIndent()
* p.printIndent()
* p.println('child 1')
* p.printIndent()
* p.println('child 2')
* p.decrementIndent()
* p.printIndent()
* p.println('parent2')
* p.flush()
* }
* </pre>
* <p>The above example prints this to standard output: </p>
* <pre>
* parent1
* child 1
* child 2
* parent2
* </pre>
* @author <a href="mailto:[email protected]">James Strachan</a>
*/
public class IndentPrinter {
private int indentLevel;
private String indent;
private Writer out;
private final boolean addNewlines;
/**
* Creates a PrintWriter pointing to System.out, with an indent of two
* spaces.
* @see #IndentPrinter(Writer, String)
*/
public IndentPrinter() {
this(new PrintWriter(System.out), " ");
}
/**
* Create an IndentPrinter to the given PrintWriter, with an indent of two
* spaces.
* @param out PrintWriter to output to
* @see #IndentPrinter(Writer, String)
*/
public IndentPrinter(Writer out) {
this(out, " ");
}
/**
* Create an IndentPrinter to the given PrintWriter
* @param out PrintWriter to output to
* @param indent character(s) used to indent each line
*/
public IndentPrinter(Writer out, String indent) {
this(out, indent, true);
}
public IndentPrinter(Writer out, String indent, boolean addNewlines) {
this.addNewlines = addNewlines;
if (out == null) {
throw new IllegalArgumentException("Must specify a PrintWriter");
}
this.out = out;
this.indent = indent;
}
public void println(String text) {
try {
out.write(text);
println();
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
public void print(String text) {
try {
out.write(text);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
public void print(char c) {
try {
out.write(c);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
/**
* Prints the current indent level.
*/
public void printIndent() {
for (int i = 0; i < indentLevel; i++) {
try {
out.write(indent);
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
}
public void println() {
if (addNewlines) {
try {
out.write("\n");
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
}
public void incrementIndent() {
++indentLevel;
}
public void decrementIndent() {
--indentLevel;
}
public int getIndentLevel() {
return indentLevel;
}
public void setIndentLevel(int indentLevel) {
this.indentLevel = indentLevel;
}
public void flush() {
try {
out.flush();
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
}
} | tweak javadoc
git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@21455 a5544e8c-8a19-0410-ba12-f9af4593a198
| src/main/groovy/util/IndentPrinter.java | tweak javadoc | <ide><path>rc/main/groovy/util/IndentPrinter.java
<ide> import java.io.Writer;
<ide>
<ide> /**
<del> * <p>A helper class for printing indented text. This can be used stand-alone or, more commonly, from Builders. </p>
<add> * <p>A helper class for printing indented text. This can be used stand-alone or, more commonly, from Builders.</p>
<ide> *
<ide> * <p>By default, a PrintWriter to System.out is used as the Writer, but it is possible
<del> * to change the Writer by passing a new one as a constructor argument. </p>
<add> * to change the Writer by passing a new one as a constructor argument.</p>
<ide> *
<ide> * <p>Indention by default is 2 characters but can be changed by passing a
<del> * different value as a constructor argument. </p>
<add> * different value as a constructor argument.</p>
<ide> *
<ide> * <p>The following is an example usage. Note that within a "with" block you need to
<ide> * specify a parameter name so that this.println is not called instead of IndentPrinter.println: </p>
<ide> private final boolean addNewlines;
<ide>
<ide> /**
<del> * Creates a PrintWriter pointing to System.out, with an indent of two
<del> * spaces.
<add> * Creates an IndentPrinter backed by a PrintWriter pointing to System.out, with an indent of two spaces.
<add> *
<ide> * @see #IndentPrinter(Writer, String)
<ide> */
<ide> public IndentPrinter() {
<ide> }
<ide>
<ide> /**
<del> * Create an IndentPrinter to the given PrintWriter, with an indent of two
<del> * spaces.
<del> * @param out PrintWriter to output to
<add> * Creates an IndentPrinter backed by the supplied Writer, with an indent of two spaces.
<add> *
<add> * @param out Writer to output to
<ide> * @see #IndentPrinter(Writer, String)
<ide> */
<ide> public IndentPrinter(Writer out) {
<ide> }
<ide>
<ide> /**
<del> * Create an IndentPrinter to the given PrintWriter
<del> * @param out PrintWriter to output to
<add> * Creates an IndentPrinter backed by the supplied Writer,
<add> * with a user-supplied String to be used for indenting.
<add> *
<add> * @param out Writer to output to
<ide> * @param indent character(s) used to indent each line
<ide> */
<ide> public IndentPrinter(Writer out, String indent) {
<ide> this(out, indent, true);
<ide> }
<ide>
<add> /**
<add> * Creates an IndentPrinter backed by the supplied Writer,
<add> * with a user-supplied String to be used for indenting
<add> * and the ability to override newline handling.
<add> *
<add> * @param out Writer to output to
<add> * @param indent character(s) used to indent each line
<add> * @param addNewlines set to false to gobble all new lines (default true)
<add> */
<ide> public IndentPrinter(Writer out, String indent, boolean addNewlines) {
<ide> this.addNewlines = addNewlines;
<ide> if (out == null) {
<del> throw new IllegalArgumentException("Must specify a PrintWriter");
<add> throw new IllegalArgumentException("Must specify a Writer");
<ide> }
<ide> this.out = out;
<ide> this.indent = indent;
<ide> }
<ide>
<add> /**
<add> * Prints a string followed by an end of line character.
<add> *
<add> * @param text String to be written
<add> */
<ide> public void println(String text) {
<ide> try {
<ide> out.write(text);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Prints a string.
<add> *
<add> * @param text String to be written
<add> */
<ide> public void print(String text) {
<ide> try {
<ide> out.write(text);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Prints a character.
<add> *
<add> * @param c char to be written
<add> */
<ide> public void print(char c) {
<ide> try {
<ide> out.write(c);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Prints an end-of-line character (if enabled via addNewLines property).
<add> * Defaults to outputting a single '\n' character but by using a custom
<add> * Writer, e.g. PlatformLineWriter, you can get platform-specific
<add> * end-of-line characters.
<add> *
<add> * @see #IndentPrinter(Writer, String, boolean)
<add> */
<ide> public void println() {
<ide> if (addNewlines) {
<ide> try { |
|
Java | apache-2.0 | 6c8ecfa45027a1a35b1dc2de2ade02e4fda3ee12 | 0 | data-integrations/database-delta-plugins | /*
* Copyright © 2020 Cask Data, 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 io.cdap.delta.mysql;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.delta.api.DDLEvent;
import io.cdap.delta.api.DDLOperation;
import io.cdap.delta.api.DMLEvent;
import io.cdap.delta.api.DMLOperation;
import io.cdap.delta.api.DeltaSourceContext;
import io.cdap.delta.api.EventEmitter;
import io.cdap.delta.api.Offset;
import io.cdap.delta.api.SourceTable;
import io.cdap.delta.common.Records;
import io.debezium.connector.mysql.MySqlValueConverters;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.relational.Tables;
import io.debezium.relational.ddl.DdlParser;
import io.debezium.relational.ddl.DdlParserListener;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* Record consumer for MySQL.
*/
public class MySqlRecordConsumer implements Consumer<SourceRecord> {
private static final Logger LOG = LoggerFactory.getLogger(MySqlRecordConsumer.class);
private final DeltaSourceContext context;
private final EventEmitter emitter;
private final DdlParser ddlParser;
private final MySqlValueConverters mySqlValueConverters;
private final Tables tables;
private final Map<String, SourceTable> sourceTableMap;
public MySqlRecordConsumer(DeltaSourceContext context, EventEmitter emitter,
DdlParser ddlParser, MySqlValueConverters mySqlValueConverters,
Tables tables, Map<String, SourceTable> sourceTableMap) {
this.context = context;
this.emitter = emitter;
this.ddlParser = ddlParser;
this.mySqlValueConverters = mySqlValueConverters;
this.tables = tables;
this.sourceTableMap = sourceTableMap;
}
@Override
public void accept(SourceRecord sourceRecord) {
/*
For ddl, struct contains 3 top level fields:
source struct
databaseName string
ddl string
Before every DDL event, a weird event with ddl='# Dum' is consumed before the actual event.
source is a struct with 14 fields:
0 - version string (debezium version)
1 - connector string
2 - name string (name of the consumer, set when creating the Configuration)
3 - server_id int64
4 - ts_sec int64
5 - gtid string
6 - file string
7 - pos int64 (there can be multiple events for the same file and position.
Everything in same position seems to be anything done in the same query)
8 - row int32 (if multiple rows are involved in the same transaction, this is the row #)
9 - snapshot boolean (null is the same as false)
10 - thread int64
11 - db string
12 - table string
13 - query string
For dml, struct contains 5 top level fields:
0 - before struct
1 - after struct
2 - source struct
3 - op string (c for create or insert, u for update, d for delete, and r for read)
not sure when 'r' happens, it's not for select queries...
4 - ts_ms int64 (this is *not* the timestamp of the event, but the timestamp when Debezium read it)
before is a struct representing the row before the operation. It will have a schema matching the table schema
after is a struct representing the row after the operation. It will have a schema matching the table schema
*/
try {
context.setOK();
} catch (IOException e) {
LOG.warn("Unable to set source state to OK.", e);
}
if (sourceRecord.value() == null) {
return;
}
Map<String, String> deltaOffset = generateCdapOffsets(sourceRecord);
Offset recordOffset = new Offset(deltaOffset);
StructuredRecord val = Records.convert((Struct) sourceRecord.value());
String ddl = val.get("ddl");
StructuredRecord source = val.get("source");
if (source == null) {
// This should not happen, 'source' is a mandatory field in sourceRecord from debezium
return;
}
boolean isSnapshot = Boolean.TRUE.equals(source.get(MySqlConstantOffsetBackingStore.SNAPSHOT));
// If the map is empty, we should read all DDL/DML events and columns of all tables
boolean readAllTables = sourceTableMap.isEmpty();
if (ddl != null) {
ddlParser.getDdlChanges().reset();
ddlParser.parse(ddl, tables);
ddlParser.getDdlChanges().groupEventsByDatabase((database, events) -> {
for (DdlParserListener.Event event : events) {
DDLEvent.Builder builder = DDLEvent.builder()
.setDatabase(database)
.setOffset(recordOffset)
.setSnapshot(isSnapshot);
// since current ddl blacklist implementation is bind with table level, we will only do the dll blacklist
// checking only for table change related ddl event, includes: ALTER_TABLE, RENAME_TABLE, DROP_TABLE,
// CREATE_TABLE and TRUNCATE_TABLE.
switch (event.type()) {
case ALTER_TABLE:
DdlParserListener.TableAlteredEvent alteredEvent = (DdlParserListener.TableAlteredEvent) event;
TableId tableId = alteredEvent.tableId();
Table table = tables.forTable(tableId);
SourceTable sourceTable = getSourceTable(database, tableId.table());
DDLOperation ddlOp;
if (alteredEvent.previousTableId() != null) {
ddlOp = DDLOperation.RENAME_TABLE;
builder.setPrevTable(alteredEvent.previousTableId().table());
} else {
ddlOp = DDLOperation.ALTER_TABLE;
}
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, ddlOp)) {
emitter.emit(builder.setOperation(ddlOp)
.setTable(tableId.table())
.setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
.setPrimaryKey(table.primaryKeyColumnNames())
.build());
}
break;
case DROP_TABLE:
DdlParserListener.TableDroppedEvent droppedEvent = (DdlParserListener.TableDroppedEvent) event;
sourceTable = getSourceTable(database, droppedEvent.tableId().table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.DROP_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.DROP_TABLE)
.setTable(droppedEvent.tableId().table())
.build());
}
break;
case CREATE_TABLE:
DdlParserListener.TableCreatedEvent createdEvent = (DdlParserListener.TableCreatedEvent) event;
tableId = createdEvent.tableId();
table = tables.forTable(tableId);
sourceTable = getSourceTable(database, tableId.table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.CREATE_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.CREATE_TABLE)
.setTable(tableId.table())
.setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
.setPrimaryKey(table.primaryKeyColumnNames())
.build());
}
break;
case DROP_DATABASE:
emitter.emit(builder.setOperation(DDLOperation.DROP_DATABASE).build());
break;
case CREATE_DATABASE:
emitter.emit(builder.setOperation(DDLOperation.CREATE_DATABASE).build());
break;
case TRUNCATE_TABLE:
DdlParserListener.TableTruncatedEvent truncatedEvent =
(DdlParserListener.TableTruncatedEvent) event;
sourceTable = getSourceTable(database, truncatedEvent.tableId().table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.TRUNCATE_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.TRUNCATE_TABLE)
.setTable(truncatedEvent.tableId().table())
.build());
}
break;
default:
return;
}
}
});
return;
}
String databaseName = source.get("db");
String tableName = source.get("table");
SourceTable sourceTable = getSourceTable(databaseName, tableName);
if (sourceTableNotValid(readAllTables, sourceTable)) {
return;
}
DMLOperation op;
String opStr = val.get("op");
if ("c".equals(opStr)) {
op = DMLOperation.INSERT;
} else if ("u".equals(opStr)) {
op = DMLOperation.UPDATE;
} else if ("d".equals(opStr)) {
op = DMLOperation.DELETE;
} else {
LOG.warn("Skipping unknown operation type '{}'", opStr);
return;
}
if (!readAllTables && sourceTable.getDmlBlacklist().contains(op)) {
// do nothing due to it was not set to read all tables and the DML op has been blacklisted for this table
return;
}
String transactionId = source.get("gtid");
if (transactionId == null) {
// this is not really a transaction id, but we don't get an event when a transaction started/ended
transactionId = String.format("%s:%d",
source.get(MySqlConstantOffsetBackingStore.FILE),
source.get(MySqlConstantOffsetBackingStore.POS));
}
StructuredRecord before = val.get("before");
StructuredRecord after = val.get("after");
if (!readAllTables) {
if (before != null) {
before = Records.keepSelectedColumns(before, sourceTable.getColumns());
}
if (after != null) {
after = Records.keepSelectedColumns(after, sourceTable.getColumns());
}
}
Long ingestTime = val.get("ts_ms");
DMLEvent.Builder builder = DMLEvent.builder()
.setOffset(recordOffset)
.setOperation(op)
.setDatabase(databaseName)
.setTable(tableName)
.setTransactionId(transactionId)
.setIngestTimestamp(ingestTime)
.setSnapshot(isSnapshot);
// It is required for the source to provide the previous row if the dml operation is 'UPDATE'
if (op == DMLOperation.UPDATE) {
emitter.emit(builder.setPreviousRow(before).setRow(after).build());
} else if (op == DMLOperation.DELETE) {
emitter.emit(builder.setRow(before).build());
} else {
emitter.emit(builder.setRow(after).build());
}
}
private boolean isDDLOperationBlacklisted(boolean readAllTables, SourceTable sourceTable, DDLOperation op) {
// return true if record consumer was not set to read all table events and the DDL op has been
// blacklisted for this table
return !readAllTables && sourceTable.getDdlBlacklist().contains(op);
}
private boolean sourceTableNotValid(boolean readAllTables, SourceTable sourceTable) {
// this should not happen, in this case, just return the result here and let caller to handle
return !readAllTables && sourceTable == null;
}
private SourceTable getSourceTable(String database, String table) {
String sourceTableId = database + "." + table;
return sourceTableMap.get(sourceTableId);
}
// This method is used for generating a cdap offsets from debezium sourceRecord.
private Map<String, String> generateCdapOffsets(SourceRecord sourceRecord) {
Map<String, String> deltaOffset = new HashMap<>();
Struct value = (Struct) sourceRecord.value();
if (value == null) { // safety check to avoid NPE
return deltaOffset;
}
Struct source = (Struct) value.get("source");
if (source == null) { // safety check to avoid NPE
return deltaOffset;
}
String binlogFile = (String) source.get(MySqlConstantOffsetBackingStore.FILE);
Long binlogPosition = (Long) source.get(MySqlConstantOffsetBackingStore.POS);
Boolean snapshot = (Boolean) source.get(MySqlConstantOffsetBackingStore.SNAPSHOT);
if (binlogFile != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.FILE, binlogFile);
}
if (binlogPosition != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.POS, String.valueOf(binlogPosition));
}
if (snapshot != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.SNAPSHOT, String.valueOf(snapshot));
}
return deltaOffset;
}
}
| mysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java | /*
* Copyright © 2020 Cask Data, 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 io.cdap.delta.mysql;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.delta.api.DDLEvent;
import io.cdap.delta.api.DDLOperation;
import io.cdap.delta.api.DMLEvent;
import io.cdap.delta.api.DMLOperation;
import io.cdap.delta.api.DeltaSourceContext;
import io.cdap.delta.api.EventEmitter;
import io.cdap.delta.api.Offset;
import io.cdap.delta.api.SourceTable;
import io.cdap.delta.common.Records;
import io.debezium.connector.mysql.MySqlValueConverters;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.relational.Tables;
import io.debezium.relational.ddl.DdlParser;
import io.debezium.relational.ddl.DdlParserListener;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* Record consumer for MySQL.
*/
public class MySqlRecordConsumer implements Consumer<SourceRecord> {
private static final Logger LOG = LoggerFactory.getLogger(MySqlRecordConsumer.class);
private final DeltaSourceContext context;
private final EventEmitter emitter;
private final DdlParser ddlParser;
private final MySqlValueConverters mySqlValueConverters;
private final Tables tables;
private final Map<String, SourceTable> sourceTableMap;
public MySqlRecordConsumer(DeltaSourceContext context, EventEmitter emitter,
DdlParser ddlParser, MySqlValueConverters mySqlValueConverters,
Tables tables, Map<String, SourceTable> sourceTableMap) {
this.context = context;
this.emitter = emitter;
this.ddlParser = ddlParser;
this.mySqlValueConverters = mySqlValueConverters;
this.tables = tables;
this.sourceTableMap = sourceTableMap;
}
@Override
public void accept(SourceRecord sourceRecord) {
/*
For ddl, struct contains 3 top level fields:
source struct
databaseName string
ddl string
Before every DDL event, a weird event with ddl='# Dum' is consumed before the actual event.
source is a struct with 14 fields:
0 - version string (debezium version)
1 - connector string
2 - name string (name of the consumer, set when creating the Configuration)
3 - server_id int64
4 - ts_sec int64
5 - gtid string
6 - file string
7 - pos int64 (there can be multiple events for the same file and position.
Everything in same position seems to be anything done in the same query)
8 - row int32 (if multiple rows are involved in the same transaction, this is the row #)
9 - snapshot boolean (null is the same as false)
10 - thread int64
11 - db string
12 - table string
13 - query string
For dml, struct contains 5 top level fields:
0 - before struct
1 - after struct
2 - source struct
3 - op string (c for create or insert, u for update, d for delete, and r for read)
not sure when 'r' happens, it's not for select queries...
4 - ts_ms int64 (this is *not* the timestamp of the event, but the timestamp when Debezium read it)
before is a struct representing the row before the operation. It will have a schema matching the table schema
after is a struct representing the row after the operation. It will have a schema matching the table schema
*/
try {
context.setOK();
} catch (IOException e) {
LOG.warn("Unable to set source state to OK.", e);
}
if (sourceRecord.value() == null) {
return;
}
Map<String, String> deltaOffset = generateCdapOffsets(sourceRecord);
Offset recordOffset = new Offset(deltaOffset);
StructuredRecord val = Records.convert((Struct) sourceRecord.value());
String ddl = val.get("ddl");
StructuredRecord source = val.get("source");
if (source == null) {
// This should not happen, 'source' is a mandatory field in sourceRecord from debezium
return;
}
boolean isSnapshot = Boolean.TRUE.equals(source.get(MySqlConstantOffsetBackingStore.SNAPSHOT));
// If the map is empty, we should read all DDL/DML events and columns of all tables
boolean readAllTables = sourceTableMap.isEmpty();
if (ddl != null) {
ddlParser.getDdlChanges().reset();
ddlParser.parse(ddl, tables);
ddlParser.getDdlChanges().groupEventsByDatabase((database, events) -> {
for (DdlParserListener.Event event : events) {
DDLEvent.Builder builder = DDLEvent.builder()
.setDatabase(database)
.setOffset(recordOffset)
.setSnapshot(isSnapshot);
// since current ddl blacklist implementation is bind with table level, we will only do the dll blacklist
// checking only for table change related ddl event(ALTER_TABLE/DROP_TABLE/CREATE_TABLE/TRUNCATE_TABLE).
switch (event.type()) {
case ALTER_TABLE:
DdlParserListener.TableAlteredEvent alteredEvent = (DdlParserListener.TableAlteredEvent) event;
TableId tableId = alteredEvent.tableId();
Table table = tables.forTable(tableId);
SourceTable sourceTable = getSourceTable(database, tableId.table());
if (alteredEvent.previousTableId() != null) {
builder.setOperation(DDLOperation.RENAME_TABLE)
.setPrevTable(alteredEvent.previousTableId().table());
} else {
builder.setOperation(DDLOperation.ALTER_TABLE);
}
emitter.emit(builder.setTable(tableId.table())
.setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
.setPrimaryKey(table.primaryKeyColumnNames())
.build());
break;
case DROP_TABLE:
DdlParserListener.TableDroppedEvent droppedEvent = (DdlParserListener.TableDroppedEvent) event;
sourceTable = getSourceTable(database, droppedEvent.tableId().table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.DROP_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.DROP_TABLE)
.setTable(droppedEvent.tableId().table())
.build());
}
break;
case CREATE_TABLE:
DdlParserListener.TableCreatedEvent createdEvent = (DdlParserListener.TableCreatedEvent) event;
tableId = createdEvent.tableId();
table = tables.forTable(tableId);
sourceTable = getSourceTable(database, tableId.table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.CREATE_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.CREATE_TABLE)
.setTable(tableId.table())
.setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
.setPrimaryKey(table.primaryKeyColumnNames())
.build());
}
break;
case DROP_DATABASE:
emitter.emit(builder.setOperation(DDLOperation.DROP_DATABASE).build());
break;
case CREATE_DATABASE:
emitter.emit(builder.setOperation(DDLOperation.CREATE_DATABASE).build());
break;
case TRUNCATE_TABLE:
DdlParserListener.TableTruncatedEvent truncatedEvent =
(DdlParserListener.TableTruncatedEvent) event;
sourceTable = getSourceTable(database, truncatedEvent.tableId().table());
if (!sourceTableNotValid(readAllTables, sourceTable) &&
!isDDLOperationBlacklisted(readAllTables, sourceTable, DDLOperation.TRUNCATE_TABLE)) {
emitter.emit(builder.setOperation(DDLOperation.TRUNCATE_TABLE)
.setTable(truncatedEvent.tableId().table())
.build());
}
break;
default:
return;
}
}
});
return;
}
String databaseName = source.get("db");
String tableName = source.get("table");
SourceTable sourceTable = getSourceTable(databaseName, tableName);
if (sourceTableNotValid(readAllTables, sourceTable)) {
return;
}
DMLOperation op;
String opStr = val.get("op");
if ("c".equals(opStr)) {
op = DMLOperation.INSERT;
} else if ("u".equals(opStr)) {
op = DMLOperation.UPDATE;
} else if ("d".equals(opStr)) {
op = DMLOperation.DELETE;
} else {
LOG.warn("Skipping unknown operation type '{}'", opStr);
return;
}
if (!readAllTables && sourceTable.getDmlBlacklist().contains(op)) {
// do nothing due to it was not set to read all tables and the DML op has been blacklisted for this table
return;
}
String transactionId = source.get("gtid");
if (transactionId == null) {
// this is not really a transaction id, but we don't get an event when a transaction started/ended
transactionId = String.format("%s:%d",
source.get(MySqlConstantOffsetBackingStore.FILE),
source.get(MySqlConstantOffsetBackingStore.POS));
}
StructuredRecord before = val.get("before");
StructuredRecord after = val.get("after");
if (!readAllTables) {
if (before != null) {
before = Records.keepSelectedColumns(before, sourceTable.getColumns());
}
if (after != null) {
after = Records.keepSelectedColumns(after, sourceTable.getColumns());
}
}
Long ingestTime = val.get("ts_ms");
DMLEvent.Builder builder = DMLEvent.builder()
.setOffset(recordOffset)
.setOperation(op)
.setDatabase(databaseName)
.setTable(tableName)
.setTransactionId(transactionId)
.setIngestTimestamp(ingestTime)
.setSnapshot(isSnapshot);
// It is required for the source to provide the previous row if the dml operation is 'UPDATE'
if (op == DMLOperation.UPDATE) {
emitter.emit(builder.setPreviousRow(before).setRow(after).build());
} else if (op == DMLOperation.DELETE) {
emitter.emit(builder.setRow(before).build());
} else {
emitter.emit(builder.setRow(after).build());
}
}
private boolean isDDLOperationBlacklisted(boolean readAllTables, SourceTable sourceTable, DDLOperation op) {
// return true if record consumer was not set to read all table events and the DDL op has been
// blacklisted for this table
return !readAllTables && sourceTable.getDdlBlacklist().contains(op);
}
private boolean sourceTableNotValid(boolean readAllTables, SourceTable sourceTable) {
// this should not happen, in this case, just return the result here and let caller to handle
return !readAllTables && sourceTable == null;
}
private SourceTable getSourceTable(String database, String table) {
String sourceTableId = database + "." + table;
return sourceTableMap.get(sourceTableId);
}
// This method is used for generating a cdap offsets from debezium sourceRecord.
private Map<String, String> generateCdapOffsets(SourceRecord sourceRecord) {
Map<String, String> deltaOffset = new HashMap<>();
Struct value = (Struct) sourceRecord.value();
if (value == null) { // safety check to avoid NPE
return deltaOffset;
}
Struct source = (Struct) value.get("source");
if (source == null) { // safety check to avoid NPE
return deltaOffset;
}
String binlogFile = (String) source.get(MySqlConstantOffsetBackingStore.FILE);
Long binlogPosition = (Long) source.get(MySqlConstantOffsetBackingStore.POS);
Boolean snapshot = (Boolean) source.get(MySqlConstantOffsetBackingStore.SNAPSHOT);
if (binlogFile != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.FILE, binlogFile);
}
if (binlogPosition != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.POS, String.valueOf(binlogPosition));
}
if (snapshot != null) {
deltaOffset.put(MySqlConstantOffsetBackingStore.SNAPSHOT, String.valueOf(snapshot));
}
return deltaOffset;
}
}
| Handle RENAME_TABLE and ALTER_TABLE together.
| mysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java | Handle RENAME_TABLE and ALTER_TABLE together. | <ide><path>ysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java
<ide> .setOffset(recordOffset)
<ide> .setSnapshot(isSnapshot);
<ide> // since current ddl blacklist implementation is bind with table level, we will only do the dll blacklist
<del> // checking only for table change related ddl event(ALTER_TABLE/DROP_TABLE/CREATE_TABLE/TRUNCATE_TABLE).
<add> // checking only for table change related ddl event, includes: ALTER_TABLE, RENAME_TABLE, DROP_TABLE,
<add> // CREATE_TABLE and TRUNCATE_TABLE.
<ide> switch (event.type()) {
<ide> case ALTER_TABLE:
<ide> DdlParserListener.TableAlteredEvent alteredEvent = (DdlParserListener.TableAlteredEvent) event;
<ide> TableId tableId = alteredEvent.tableId();
<ide> Table table = tables.forTable(tableId);
<ide> SourceTable sourceTable = getSourceTable(database, tableId.table());
<del>
<add> DDLOperation ddlOp;
<ide> if (alteredEvent.previousTableId() != null) {
<del> builder.setOperation(DDLOperation.RENAME_TABLE)
<del> .setPrevTable(alteredEvent.previousTableId().table());
<add> ddlOp = DDLOperation.RENAME_TABLE;
<add> builder.setPrevTable(alteredEvent.previousTableId().table());
<ide> } else {
<del> builder.setOperation(DDLOperation.ALTER_TABLE);
<del> }
<del> emitter.emit(builder.setTable(tableId.table())
<del> .setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
<del> Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
<del> .setPrimaryKey(table.primaryKeyColumnNames())
<del> .build());
<add> ddlOp = DDLOperation.ALTER_TABLE;
<add> }
<add>
<add> if (!sourceTableNotValid(readAllTables, sourceTable) &&
<add> !isDDLOperationBlacklisted(readAllTables, sourceTable, ddlOp)) {
<add> emitter.emit(builder.setOperation(ddlOp)
<add> .setTable(tableId.table())
<add> .setSchema(readAllTables ? Records.getSchema(table, mySqlValueConverters) :
<add> Records.getSchema(table, mySqlValueConverters, sourceTable.getColumns()))
<add> .setPrimaryKey(table.primaryKeyColumnNames())
<add> .build());
<add> }
<ide> break;
<ide> case DROP_TABLE:
<ide> DdlParserListener.TableDroppedEvent droppedEvent = (DdlParserListener.TableDroppedEvent) event; |
|
JavaScript | apache-2.0 | 71fc0fe56509af20318cb5ad86c1b72e45efbf08 | 0 | mwaylabs/uikit,mwaylabs/uikit,mwaylabs/uikit | 'use strict';
angular.module('mwModal', [])
/**
*
* @ngdoc object
* @name mwModal.Modal
* @description The Modal service is used to manage Bootstrap modals.
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope, Modal) {
* var modal = Modal.create({
* templateUrl: 'myModal.html',
* scope: $scope,
* controller: function() {
* // do something on initialization
* }
* });
* $scope.onClick = function() {
* Modal.show(modal)
* }
* }
* </script>
* </doc:source>
* </doc:example>
*/
.service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {
var body = $document.find('body').eq(0);
var Modal = function (modalOptions) {
var _id = modalOptions.templateUrl,
_scope = modalOptions.scope || $rootScope,
_scopeAttributes = modalOptions.scopeAttributes || {},
_controller = modalOptions.controller,
_class = modalOptions.class || '',
_holderEl = modalOptions.el || 'body div[ng-view]',
_modalOpened = false,
_self = this,
_cachedTemplate,
_modal,
_usedScope,
_bootstrapModal;
var _getTemplate = function () {
if (!_id) {
throw new Error('Modal service: templateUrl options is required.');
}
// Get template from cache
_cachedTemplate = $templateCache.get(_id);
if (_cachedTemplate) {
return $q.when(_cachedTemplate);
} else {
return $http.get(_id).then(function (resp) {
$templateCache.put(_id, resp.data);
return resp.data;
}, function () {
throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
});
}
};
var _bindModalCloseEvent = function () {
_bootstrapModal.on('hidden.bs.modal', function () {
_self.destroy();
});
};
var _destroyOnRouteChange = function(){
var changeLocationOff = $rootScope.$on('$locationChangeStart', function (ev, newUrl) {
if(_bootstrapModal && _modalOpened){
ev.preventDefault();
_self.hide().then(function(){
document.location.href=newUrl;
changeLocationOff();
});
}
});
};
var _buildModal = function () {
var dfd = $q.defer();
_usedScope = _scope.$new();
_.extend(_usedScope, _scopeAttributes);
if (_controller) {
$controller(_controller, {$scope: _usedScope, modalId: _id});
}
_scope.hideModal = function () {
return _self.hide();
};
_getTemplate().then(function (template) {
_modal = $compile(template.trim())(_usedScope);
_usedScope.$on('COMPILE:FINISHED', function () {
_modal.addClass('mw-modal');
_modal.addClass(_class);
_bootstrapModal = _modal.find('.modal');
_bindModalCloseEvent();
_destroyOnRouteChange();
dfd.resolve();
});
});
return dfd.promise;
};
this.getScope = function () {
return _scope;
};
/**
*
* @ngdoc function
* @name mwModal.Modal#show
* @methodOf mwModal.Modal
* @function
* @description Shows the modal
*/
this.show = function () {
body.css({
height: '100%',
width: '100%',
overflow: 'hidden'
});
_buildModal().then(function () {
angular.element(_holderEl).append(_modal);
_bootstrapModal.modal('show');
_modalOpened = true;
});
};
this.setScopeAttributes = function (obj) {
if (_.isObject(obj)) {
_.extend(_scopeAttributes, obj);
}
};
/**
*
* @ngdoc function
* @name mwModal.Modal#hide
* @methodOf mwModal.Modal
* @function
* @description Hides the modal
* @returns {Object} Promise which will be resolved when modal is successfully closed
*/
this.hide = function () {
var dfd = $q.defer();
if (_bootstrapModal) {
_bootstrapModal.one('hidden.bs.modal', function () {
_bootstrapModal.off();
_self.destroy();
_modalOpened = false;
dfd.resolve();
});
_bootstrapModal.modal('hide');
} else {
dfd.reject();
}
return dfd.promise;
};
/**
*
* @ngdoc function
* @name mwModal.Modal#toggle
* @methodOf mwModal.Modal
* @function
* @description Toggles the modal
* @param {String} modalId Modal identifier
*/
this.toggle = function () {
_bootstrapModal.modal('toggle');
};
/**
*
* @ngdoc function
* @name mwModal.Modal#destroy
* @methodOf mwModal.Modal
* @function
* @description Removes the modal from the dom
*/
this.destroy = function () {
body.css({
height: '',
width: '',
overflow: ''
});
if (_modal) {
_usedScope.$destroy();
_modal.remove();
}
};
(function main() {
_getTemplate();
_scope.$on('$destroy', function () {
_self.hide();
});
})();
};
/**
*
* @ngdoc function
* @name mwModal.Modal#create
* @methodOf mwModal.Modal
* @function
* @description Create and initialize the modal element in the DOM. Available options
*
* - **templateUrl**: URL to a template (_required_)
* - **scope**: scope that should be available in the controller
* - **controller**: controller instance for the modal
*
* @param {Object} modalOptions The options of the modal which are used to instantiate it
* @returns {Object} Modal
*/
this.create = function (modalOptions) {
return new Modal(modalOptions);
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModal
* @element div
* @description
* Shortcut directive for Bootstraps modal.
*
* @scope
*
* @param {string} title Modal title
* @example
* <doc:example>
* <doc:source>
* <div mw-modal title="My modal">
* <div mw-modal-body>
* <p>One fine body…</p>
* </div>
* <div mw-modal-footer>
* <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
* <button type="button" class="btn btn-primary">Save changes</button>
* </div>
* </div>
* </doc:source>
* </doc:example>
*/
.directive('mwModal', function () {
return {
restrict: 'A',
scope: {
title: '@'
},
transclude: true,
templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
link: function (scope) {
scope.$emit('COMPILE:FINISHED');
}
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalBody
* @element div
* @description
* Shortcut directive for Bootstraps body. See {@link mwModal.directive:mwModal `mwModal`} for more information
* about mwModal.
*/
.directive('mwModalBody', function () {
return {
restrict: 'A',
transclude: true,
replace: true,
template: '<div class="modal-body clearfix" ng-transclude></div>'
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalFooter
* @element div
* @description
* Shortcut directive for Bootstraps footer. See {@link mwModal.directive:mwModal `mwModal`} for more information
* about mwModal.
*/
.directive('mwModalFooter', function () {
return {
restrict: 'A',
transclude: true,
replace: true,
template: '<div class="modal-footer" ng-transclude></div>'
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalOnEnter
* @element button
* @description
* Adds ability to trigger button with enter key. Checks validation if button is part of a form.
*/
.directive('mwModalOnEnter', function () {
return {
restrict: 'A',
require: '?^form',
link: function (scope, elm, attr, ctrl) {
elm.parents('.modal').first().on('keyup', function (event) {
if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
if ((ctrl && ctrl.$valid) || !ctrl) {
elm.click();
}
}
});
}
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalConfirm
* @element div
* @description
*
* Opens a simple confirm modal.
*
* @scope
*
* @param {expression} ok Expression to evaluate on click on 'ok' button
* @param {expression} cancel Expression to evaluate on click on 'cancel' button
*/
.directive('mwModalConfirm', function () {
return {
restrict: 'A',
transclude: true,
scope: true,
templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
link: function (scope, elm, attr) {
angular.forEach(['ok', 'cancel'], function (action) {
scope[action] = function () {
scope.$eval(attr[action]);
};
});
}
};
}); | mwModal.js | 'use strict';
angular.module('mwModal', [])
/**
*
* @ngdoc object
* @name mwModal.Modal
* @description The Modal service is used to manage Bootstrap modals.
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope, Modal) {
* var modal = Modal.create({
* templateUrl: 'myModal.html',
* scope: $scope,
* controller: function() {
* // do something on initialization
* }
* });
* $scope.onClick = function() {
* Modal.show(modal)
* }
* }
* </script>
* </doc:source>
* </doc:example>
*/
.service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {
var body = $document.find('body').eq(0);
var Modal = function(modalOptions){
var _id = modalOptions.templateUrl,
_scope = modalOptions.scope || $rootScope,
_scopeAttributes = modalOptions.scopeAttributes || {},
_controller = modalOptions.controller,
_class = modalOptions.class || '',
_holderEl = modalOptions.el || 'body div[ng-view]',
_self = this,
_cachedTemplate,
_modal,
_usedScope,
_bootstrapModal;
var _getTemplate = function () {
if (!_id) {
throw new Error('Modal service: templateUrl options is required.');
}
// Get template from cache
_cachedTemplate = $templateCache.get(_id);
if (_cachedTemplate) {
return $q.when(_cachedTemplate);
} else {
return $http.get(_id).then(function (resp) {
$templateCache.put(_id, resp.data);
return resp.data;
}, function () {
throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
});
}
};
var _bindModalCloseEvent = function(){
_bootstrapModal.on('hidden.bs.modal',function(){
_self.destroy();
});
};
var _buildModal = function(){
var dfd = $q.defer();
_usedScope = _scope.$new();
_.extend(_usedScope, _scopeAttributes);
if (_controller) {
$controller(_controller, { $scope: _usedScope, modalId: _id });
}
_scope.hideModal = function(){
return _self.hide();
};
_getTemplate().then(function(template){
_modal = $compile(template.trim())(_usedScope);
_usedScope.$on('COMPILE:FINISHED',function(){
_modal.addClass('mw-modal');
_modal.addClass(_class);
_bootstrapModal = _modal.find('.modal');
_bindModalCloseEvent();
dfd.resolve();
});
});
return dfd.promise;
};
this.getScope = function(){
return _scope;
};
/**
*
* @ngdoc function
* @name mwModal.Modal#show
* @methodOf mwModal.Modal
* @function
* @description Shows the modal
*/
this.show = function () {
body.css({
height:'100%',
width: '100%',
overflow:'hidden'
});
_buildModal().then(function(){
angular.element(_holderEl).append(_modal);
_bootstrapModal.modal('show');
});
};
this.setScopeAttributes = function(obj){
if(_.isObject(obj)){
_.extend(_scopeAttributes, obj);
}
};
/**
*
* @ngdoc function
* @name mwModal.Modal#hide
* @methodOf mwModal.Modal
* @function
* @description Hides the modal
* @returns {Object} Promise which will be resolved when modal is successfully closed
*/
this.hide = function () {
var dfd = $q.defer();
if(_bootstrapModal){
_bootstrapModal.one('hidden.bs.modal', function () {
_bootstrapModal.off();
_self.destroy();
dfd.resolve();
});
_bootstrapModal.modal('hide');
} else {
dfd.reject();
}
return dfd.promise;
};
/**
*
* @ngdoc function
* @name mwModal.Modal#toggle
* @methodOf mwModal.Modal
* @function
* @description Toggles the modal
* @param {String} modalId Modal identifier
*/
this.toggle = function () {
_bootstrapModal.modal('toggle');
};
/**
*
* @ngdoc function
* @name mwModal.Modal#destroy
* @methodOf mwModal.Modal
* @function
* @description Removes the modal from the dom
*/
this.destroy = function () {
body.css({
height:'',
width: '',
overflow:''
});
if(_modal){
_usedScope.$destroy();
_modal.remove();
}
};
(function main(){
_getTemplate();
_scope.$on('$destroy', function () {
_self.hide();
});
$rootScope.$on('$routeChangeSuccess', function(){
if(_bootstrapModal && _bootstrapModal.data('bs.modal')){
_bootstrapModal.data('bs.modal').hideModal();
}
});
})();
};
/**
*
* @ngdoc function
* @name mwModal.Modal#create
* @methodOf mwModal.Modal
* @function
* @description Create and initialize the modal element in the DOM. Available options
*
* - **templateUrl**: URL to a template (_required_)
* - **scope**: scope that should be available in the controller
* - **controller**: controller instance for the modal
*
* @param {Object} modalOptions The options of the modal which are used to instantiate it
* @returns {Object} Modal
*/
this.create = function (modalOptions) {
return new Modal(modalOptions);
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModal
* @element div
* @description
* Shortcut directive for Bootstraps modal.
*
* @scope
*
* @param {string} title Modal title
* @example
* <doc:example>
* <doc:source>
* <div mw-modal title="My modal">
* <div mw-modal-body>
* <p>One fine body…</p>
* </div>
* <div mw-modal-footer>
* <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
* <button type="button" class="btn btn-primary">Save changes</button>
* </div>
* </div>
* </doc:source>
* </doc:example>
*/
.directive('mwModal', function () {
return {
restrict: 'A',
scope: {
title: '@'
},
transclude: true,
templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
link:function(scope){
scope.$emit('COMPILE:FINISHED');
}
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalBody
* @element div
* @description
* Shortcut directive for Bootstraps body. See {@link mwModal.directive:mwModal `mwModal`} for more information
* about mwModal.
*/
.directive('mwModalBody', function () {
return {
restrict: 'A',
transclude: true,
replace: true,
template: '<div class="modal-body clearfix" ng-transclude></div>'
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalFooter
* @element div
* @description
* Shortcut directive for Bootstraps footer. See {@link mwModal.directive:mwModal `mwModal`} for more information
* about mwModal.
*/
.directive('mwModalFooter', function () {
return {
restrict: 'A',
transclude: true,
replace: true,
template: '<div class="modal-footer" ng-transclude></div>'
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalOnEnter
* @element button
* @description
* Adds ability to trigger button with enter key. Checks validation if button is part of a form.
*/
.directive('mwModalOnEnter', function () {
return {
restrict: 'A',
require: '?^form',
link: function (scope, elm, attr, ctrl) {
elm.parents('.modal').first().on('keyup', function (event) {
if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
if ((ctrl && ctrl.$valid) || !ctrl) {
elm.click();
}
}
});
}
};
})
/**
* @ngdoc directive
* @name mwModal.directive:mwModalConfirm
* @element div
* @description
*
* Opens a simple confirm modal.
*
* @scope
*
* @param {expression} ok Expression to evaluate on click on 'ok' button
* @param {expression} cancel Expression to evaluate on click on 'cancel' button
*/
.directive('mwModalConfirm', function () {
return {
restrict: 'A',
transclude: true,
scope: true,
templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
link: function (scope, elm, attr) {
angular.forEach(['ok', 'cancel'], function (action) {
scope[action] = function () {
scope.$eval(attr[action]);
};
});
}
};
}); | prevents routing when modal is opened. Waits until it is closed and navigates then to the next url
| mwModal.js | prevents routing when modal is opened. Waits until it is closed and navigates then to the next url | <ide><path>wModal.js
<ide> * </doc:source>
<ide> * </doc:example>
<ide> */
<del> .service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {
<del>
<del> var body = $document.find('body').eq(0);
<del>
<del> var Modal = function(modalOptions){
<del>
<del> var _id = modalOptions.templateUrl,
<del> _scope = modalOptions.scope || $rootScope,
<del> _scopeAttributes = modalOptions.scopeAttributes || {},
<del> _controller = modalOptions.controller,
<del> _class = modalOptions.class || '',
<del> _holderEl = modalOptions.el || 'body div[ng-view]',
<del> _self = this,
<del> _cachedTemplate,
<del> _modal,
<del> _usedScope,
<del> _bootstrapModal;
<del>
<del>
<del> var _getTemplate = function () {
<del> if (!_id) {
<del> throw new Error('Modal service: templateUrl options is required.');
<del> }
<del>
<del> // Get template from cache
<del> _cachedTemplate = $templateCache.get(_id);
<del>
<del> if (_cachedTemplate) {
<del> return $q.when(_cachedTemplate);
<del> } else {
<del> return $http.get(_id).then(function (resp) {
<del> $templateCache.put(_id, resp.data);
<del> return resp.data;
<del> }, function () {
<del> throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
<add> .service('Modal', function ($rootScope, $templateCache, $document, $compile, $controller, $q, $http) {
<add>
<add> var body = $document.find('body').eq(0);
<add>
<add> var Modal = function (modalOptions) {
<add>
<add> var _id = modalOptions.templateUrl,
<add> _scope = modalOptions.scope || $rootScope,
<add> _scopeAttributes = modalOptions.scopeAttributes || {},
<add> _controller = modalOptions.controller,
<add> _class = modalOptions.class || '',
<add> _holderEl = modalOptions.el || 'body div[ng-view]',
<add> _modalOpened = false,
<add> _self = this,
<add> _cachedTemplate,
<add> _modal,
<add> _usedScope,
<add> _bootstrapModal;
<add>
<add>
<add> var _getTemplate = function () {
<add> if (!_id) {
<add> throw new Error('Modal service: templateUrl options is required.');
<add> }
<add>
<add> // Get template from cache
<add> _cachedTemplate = $templateCache.get(_id);
<add>
<add> if (_cachedTemplate) {
<add> return $q.when(_cachedTemplate);
<add> } else {
<add> return $http.get(_id).then(function (resp) {
<add> $templateCache.put(_id, resp.data);
<add> return resp.data;
<add> }, function () {
<add> throw new Error('Modal service: template \'' + _id + '\' has not been found. Does a template with this ID/Path exist?');
<add> });
<add> }
<add> };
<add>
<add> var _bindModalCloseEvent = function () {
<add> _bootstrapModal.on('hidden.bs.modal', function () {
<add> _self.destroy();
<add> });
<add> };
<add>
<add> var _destroyOnRouteChange = function(){
<add> var changeLocationOff = $rootScope.$on('$locationChangeStart', function (ev, newUrl) {
<add> if(_bootstrapModal && _modalOpened){
<add> ev.preventDefault();
<add> _self.hide().then(function(){
<add> document.location.href=newUrl;
<add> changeLocationOff();
<ide> });
<ide> }
<add> });
<add> };
<add>
<add> var _buildModal = function () {
<add> var dfd = $q.defer();
<add>
<add> _usedScope = _scope.$new();
<add>
<add> _.extend(_usedScope, _scopeAttributes);
<add>
<add> if (_controller) {
<add> $controller(_controller, {$scope: _usedScope, modalId: _id});
<add> }
<add>
<add> _scope.hideModal = function () {
<add> return _self.hide();
<ide> };
<ide>
<del> var _bindModalCloseEvent = function(){
<del> _bootstrapModal.on('hidden.bs.modal',function(){
<del> _self.destroy();
<add> _getTemplate().then(function (template) {
<add> _modal = $compile(template.trim())(_usedScope);
<add> _usedScope.$on('COMPILE:FINISHED', function () {
<add> _modal.addClass('mw-modal');
<add> _modal.addClass(_class);
<add> _bootstrapModal = _modal.find('.modal');
<add> _bindModalCloseEvent();
<add> _destroyOnRouteChange();
<add> dfd.resolve();
<ide> });
<del> };
<del>
<del> var _buildModal = function(){
<del> var dfd = $q.defer();
<del>
<del> _usedScope = _scope.$new();
<del>
<del> _.extend(_usedScope, _scopeAttributes);
<del>
<del> if (_controller) {
<del> $controller(_controller, { $scope: _usedScope, modalId: _id });
<del> }
<del>
<del> _scope.hideModal = function(){
<del> return _self.hide();
<del> };
<del>
<del> _getTemplate().then(function(template){
<del> _modal = $compile(template.trim())(_usedScope);
<del> _usedScope.$on('COMPILE:FINISHED',function(){
<del> _modal.addClass('mw-modal');
<del> _modal.addClass(_class);
<del> _bootstrapModal = _modal.find('.modal');
<del> _bindModalCloseEvent();
<del> dfd.resolve();
<del> });
<del> });
<del>
<del> return dfd.promise;
<del> };
<del>
<del> this.getScope = function(){
<del> return _scope;
<del> };
<del>
<del> /**
<del> *
<del> * @ngdoc function
<del> * @name mwModal.Modal#show
<del> * @methodOf mwModal.Modal
<del> * @function
<del> * @description Shows the modal
<del> */
<del> this.show = function () {
<del> body.css({
<del> height:'100%',
<del> width: '100%',
<del> overflow:'hidden'
<del> });
<del> _buildModal().then(function(){
<del> angular.element(_holderEl).append(_modal);
<del> _bootstrapModal.modal('show');
<del> });
<del> };
<del>
<del>
<del> this.setScopeAttributes = function(obj){
<del> if(_.isObject(obj)){
<del> _.extend(_scopeAttributes, obj);
<del> }
<del> };
<del>
<del> /**
<del> *
<del> * @ngdoc function
<del> * @name mwModal.Modal#hide
<del> * @methodOf mwModal.Modal
<del> * @function
<del> * @description Hides the modal
<del> * @returns {Object} Promise which will be resolved when modal is successfully closed
<del> */
<del> this.hide = function () {
<del> var dfd = $q.defer();
<del> if(_bootstrapModal){
<del> _bootstrapModal.one('hidden.bs.modal', function () {
<del> _bootstrapModal.off();
<del> _self.destroy();
<del> dfd.resolve();
<del> });
<del> _bootstrapModal.modal('hide');
<del> } else {
<del> dfd.reject();
<del> }
<del>
<del> return dfd.promise;
<del> };
<del>
<del> /**
<del> *
<del> * @ngdoc function
<del> * @name mwModal.Modal#toggle
<del> * @methodOf mwModal.Modal
<del> * @function
<del> * @description Toggles the modal
<del> * @param {String} modalId Modal identifier
<del> */
<del> this.toggle = function () {
<del> _bootstrapModal.modal('toggle');
<del> };
<del>
<del> /**
<del> *
<del> * @ngdoc function
<del> * @name mwModal.Modal#destroy
<del> * @methodOf mwModal.Modal
<del> * @function
<del> * @description Removes the modal from the dom
<del> */
<del> this.destroy = function () {
<del> body.css({
<del> height:'',
<del> width: '',
<del> overflow:''
<del> });
<del> if(_modal){
<del> _usedScope.$destroy();
<del> _modal.remove();
<del> }
<del> };
<del>
<del> (function main(){
<del>
<del> _getTemplate();
<del>
<del> _scope.$on('$destroy', function () {
<del> _self.hide();
<del> });
<del>
<del> $rootScope.$on('$routeChangeSuccess', function(){
<del> if(_bootstrapModal && _bootstrapModal.data('bs.modal')){
<del> _bootstrapModal.data('bs.modal').hideModal();
<del> }
<del> });
<del>
<del> })();
<del>
<add> });
<add>
<add> return dfd.promise;
<add> };
<add>
<add> this.getScope = function () {
<add> return _scope;
<ide> };
<ide>
<ide> /**
<ide> *
<ide> * @ngdoc function
<del> * @name mwModal.Modal#create
<add> * @name mwModal.Modal#show
<ide> * @methodOf mwModal.Modal
<ide> * @function
<del> * @description Create and initialize the modal element in the DOM. Available options
<add> * @description Shows the modal
<add> */
<add> this.show = function () {
<add> body.css({
<add> height: '100%',
<add> width: '100%',
<add> overflow: 'hidden'
<add> });
<add> _buildModal().then(function () {
<add> angular.element(_holderEl).append(_modal);
<add> _bootstrapModal.modal('show');
<add> _modalOpened = true;
<add> });
<add> };
<add>
<add>
<add> this.setScopeAttributes = function (obj) {
<add> if (_.isObject(obj)) {
<add> _.extend(_scopeAttributes, obj);
<add> }
<add> };
<add>
<add> /**
<ide> *
<del> * - **templateUrl**: URL to a template (_required_)
<del> * - **scope**: scope that should be available in the controller
<del> * - **controller**: controller instance for the modal
<add> * @ngdoc function
<add> * @name mwModal.Modal#hide
<add> * @methodOf mwModal.Modal
<add> * @function
<add> * @description Hides the modal
<add> * @returns {Object} Promise which will be resolved when modal is successfully closed
<add> */
<add> this.hide = function () {
<add> var dfd = $q.defer();
<add> if (_bootstrapModal) {
<add> _bootstrapModal.one('hidden.bs.modal', function () {
<add> _bootstrapModal.off();
<add> _self.destroy();
<add> _modalOpened = false;
<add> dfd.resolve();
<add> });
<add> _bootstrapModal.modal('hide');
<add> } else {
<add> dfd.reject();
<add> }
<add>
<add> return dfd.promise;
<add> };
<add>
<add> /**
<ide> *
<del> * @param {Object} modalOptions The options of the modal which are used to instantiate it
<del> * @returns {Object} Modal
<add> * @ngdoc function
<add> * @name mwModal.Modal#toggle
<add> * @methodOf mwModal.Modal
<add> * @function
<add> * @description Toggles the modal
<add> * @param {String} modalId Modal identifier
<ide> */
<del> this.create = function (modalOptions) {
<del> return new Modal(modalOptions);
<del> };
<del> })
<add> this.toggle = function () {
<add> _bootstrapModal.modal('toggle');
<add> };
<add>
<add> /**
<add> *
<add> * @ngdoc function
<add> * @name mwModal.Modal#destroy
<add> * @methodOf mwModal.Modal
<add> * @function
<add> * @description Removes the modal from the dom
<add> */
<add> this.destroy = function () {
<add> body.css({
<add> height: '',
<add> width: '',
<add> overflow: ''
<add> });
<add> if (_modal) {
<add> _usedScope.$destroy();
<add> _modal.remove();
<add> }
<add> };
<add>
<add> (function main() {
<add>
<add> _getTemplate();
<add>
<add> _scope.$on('$destroy', function () {
<add> _self.hide();
<add> });
<add>
<add> })();
<add>
<add> };
<add>
<add> /**
<add> *
<add> * @ngdoc function
<add> * @name mwModal.Modal#create
<add> * @methodOf mwModal.Modal
<add> * @function
<add> * @description Create and initialize the modal element in the DOM. Available options
<add> *
<add> * - **templateUrl**: URL to a template (_required_)
<add> * - **scope**: scope that should be available in the controller
<add> * - **controller**: controller instance for the modal
<add> *
<add> * @param {Object} modalOptions The options of the modal which are used to instantiate it
<add> * @returns {Object} Modal
<add> */
<add> this.create = function (modalOptions) {
<add> return new Modal(modalOptions);
<add> };
<add> })
<ide>
<ide>
<ide> /**
<ide> * </doc:example>
<ide> */
<ide>
<del> .directive('mwModal', function () {
<del> return {
<del> restrict: 'A',
<del> scope: {
<del> title: '@'
<del> },
<del> transclude: true,
<del> templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
<del> link:function(scope){
<del> scope.$emit('COMPILE:FINISHED');
<del> }
<del> };
<del> })
<add> .directive('mwModal', function () {
<add> return {
<add> restrict: 'A',
<add> scope: {
<add> title: '@'
<add> },
<add> transclude: true,
<add> templateUrl: 'modules/ui/templates/mwModal/mwModal.html',
<add> link: function (scope) {
<add> scope.$emit('COMPILE:FINISHED');
<add> }
<add> };
<add> })
<ide>
<ide> /**
<ide> * @ngdoc directive
<ide> * Shortcut directive for Bootstraps body. See {@link mwModal.directive:mwModal `mwModal`} for more information
<ide> * about mwModal.
<ide> */
<del> .directive('mwModalBody', function () {
<del> return {
<del> restrict: 'A',
<del> transclude: true,
<del> replace: true,
<del> template: '<div class="modal-body clearfix" ng-transclude></div>'
<del> };
<del> })
<add> .directive('mwModalBody', function () {
<add> return {
<add> restrict: 'A',
<add> transclude: true,
<add> replace: true,
<add> template: '<div class="modal-body clearfix" ng-transclude></div>'
<add> };
<add> })
<ide>
<ide> /**
<ide> * @ngdoc directive
<ide> * Shortcut directive for Bootstraps footer. See {@link mwModal.directive:mwModal `mwModal`} for more information
<ide> * about mwModal.
<ide> */
<del> .directive('mwModalFooter', function () {
<del> return {
<del> restrict: 'A',
<del> transclude: true,
<del> replace: true,
<del> template: '<div class="modal-footer" ng-transclude></div>'
<del> };
<del> })
<add> .directive('mwModalFooter', function () {
<add> return {
<add> restrict: 'A',
<add> transclude: true,
<add> replace: true,
<add> template: '<div class="modal-footer" ng-transclude></div>'
<add> };
<add> })
<ide>
<ide> /**
<ide> * @ngdoc directive
<ide> * @description
<ide> * Adds ability to trigger button with enter key. Checks validation if button is part of a form.
<ide> */
<del> .directive('mwModalOnEnter', function () {
<del> return {
<del> restrict: 'A',
<del> require: '?^form',
<del> link: function (scope, elm, attr, ctrl) {
<del> elm.parents('.modal').first().on('keyup', function (event) {
<del> if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
<del> if ((ctrl && ctrl.$valid) || !ctrl) {
<del> elm.click();
<del> }
<add> .directive('mwModalOnEnter', function () {
<add> return {
<add> restrict: 'A',
<add> require: '?^form',
<add> link: function (scope, elm, attr, ctrl) {
<add> elm.parents('.modal').first().on('keyup', function (event) {
<add> if (event.keyCode === 13 && event.target.nodeName !== 'SELECT') {
<add> if ((ctrl && ctrl.$valid) || !ctrl) {
<add> elm.click();
<ide> }
<del> });
<del> }
<del> };
<del> })
<add> }
<add> });
<add> }
<add> };
<add> })
<ide>
<ide> /**
<ide> * @ngdoc directive
<ide> * @param {expression} ok Expression to evaluate on click on 'ok' button
<ide> * @param {expression} cancel Expression to evaluate on click on 'cancel' button
<ide> */
<del> .directive('mwModalConfirm', function () {
<del> return {
<del> restrict: 'A',
<del> transclude: true,
<del> scope: true,
<del> templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
<del> link: function (scope, elm, attr) {
<del> angular.forEach(['ok', 'cancel'], function (action) {
<del> scope[action] = function () {
<del> scope.$eval(attr[action]);
<del> };
<del> });
<del>
<del> }
<del> };
<del> });
<add> .directive('mwModalConfirm', function () {
<add> return {
<add> restrict: 'A',
<add> transclude: true,
<add> scope: true,
<add> templateUrl: 'modules/ui/templates/mwModal/mwModalConfirm.html',
<add> link: function (scope, elm, attr) {
<add> angular.forEach(['ok', 'cancel'], function (action) {
<add> scope[action] = function () {
<add> scope.$eval(attr[action]);
<add> };
<add> });
<add>
<add> }
<add> };
<add> }); |
|
Java | apache-2.0 | a2c380f9447022b388744fbcef453e25441b7529 | 0 | zerodengxinchao/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine | package org.ovirt.engine.core.bll.snapshots;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.VmHandler;
import org.ovirt.engine.core.bll.context.CompensationContext;
import org.ovirt.engine.core.bll.memory.MemoryUtils;
import org.ovirt.engine.core.bll.network.VmInterfaceManager;
import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolManagerStrategy;
import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolPerDcSingleton;
import org.ovirt.engine.core.bll.network.vm.VnicProfileHelper;
import org.ovirt.engine.core.bll.utils.ClusterUtils;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.aaa.DbUser;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.ImageStorageDomainMap;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.BaseDiskDao;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.DiskImageDAO;
import org.ovirt.engine.core.dao.QuotaDAO;
import org.ovirt.engine.core.dao.SnapshotDao;
import org.ovirt.engine.core.dao.VdsGroupDAO;
import org.ovirt.engine.core.dao.VmDeviceDAO;
import org.ovirt.engine.core.dao.VmDynamicDAO;
import org.ovirt.engine.core.dao.VmStaticDAO;
import org.ovirt.engine.core.dao.VmTemplateDAO;
import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao;
import org.ovirt.engine.core.utils.ovf.OvfManager;
import org.ovirt.engine.core.utils.ovf.OvfReaderException;
import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link Snapshot} manager is used to easily add/update/remove snapshots.
*/
public class SnapshotsManager {
private final static Logger log = LoggerFactory.getLogger(SnapshotsManager.class);
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
"",
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the created snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
snapshotStatus,
"",
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param memoryVolume
* The memory state for the created snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
String memoryVolume,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
memoryVolume,
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param memoryVolume
* The memory state for the created snapshot
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
memoryVolume,
disks,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created with the given status {@link SnapshotStatus}.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the snapshot
* @param compensationContext
* Context for saving compensation details.
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
String memoryVolume,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
snapshotStatus,
memoryVolume,
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created with the given status {@link SnapshotStatus}.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the snapshot
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId,
"Active VM",
snapshotStatus,
SnapshotType.ACTIVE,
vm,
false,
memoryVolume,
disks,
compensationContext);
}
/**
* Add a new snapshot, saving it to the DB (with compensation). The VM's current configuration (including Disks &
* NICs) will be saved in the snapshot.<br>
* The snapshot is created in status {@link SnapshotStatus#LOCKED} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param description
* The snapshot description.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to save in configuration.
* @param memoryVolume
* the volume in which the snapshot's memory is stored
* @param compensationContext
* Context for saving compensation details.
* @return the added snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotType snapshotType,
VM vm,
String memoryVolume,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId, description, SnapshotStatus.LOCKED,
snapshotType, vm, true, memoryVolume, null, compensationContext);
}
/**
* Add a new snapshot, saving it to the DB (with compensation). The VM's current configuration (including Disks &
* NICs) will be saved in the snapshot.<br>
* The snapshot is created in status {@link SnapshotStatus#LOCKED} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param description
* The snapshot description.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to save in configuration.
* @param memoryVolume
* the volume in which the snapshot's memory is stored
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the added snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotType snapshotType,
VM vm,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId, description, SnapshotStatus.LOCKED,
snapshotType, vm, true, memoryVolume, disks, compensationContext);
}
/**addSnapshot
* Save snapshot to DB with compensation data.
*
* @param snapshotId
* The snapshot ID.
* @param description
* The snapshot description.
* @param snapshotStatus
* The snapshot status.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to link to & save configuration for (if necessary).
* @param saveVmConfiguration
* Should VM configuration be generated and saved?
* @param compensationContext
* In case compensation is needed.
* @return the saved snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotStatus snapshotStatus,
SnapshotType snapshotType,
VM vm,
boolean saveVmConfiguration,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId,
description,
snapshotStatus,
snapshotType,
vm,
saveVmConfiguration,
memoryVolume,
disks,
null,
compensationContext);
}
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotStatus snapshotStatus,
SnapshotType snapshotType,
VM vm,
boolean saveVmConfiguration,
String memoryVolume,
List<DiskImage> disks,
Map<Guid, VmDevice> vmDevices,
final CompensationContext compensationContext) {
final Snapshot snapshot = new Snapshot(snapshotId,
snapshotStatus,
vm.getId(),
saveVmConfiguration ? generateVmConfiguration(vm, disks, vmDevices) : null,
snapshotType,
description,
new Date(),
vm.getAppList(),
memoryVolume);
getSnapshotDao().save(snapshot);
compensationContext.snapshotNewEntity(snapshot);
return snapshot;
}
/**
* Generate a string containing the given VM's configuration.
*
* @param vm
* The VM to generate configuration from.
* @return A String containing the VM configuration.
*/
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) {
if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) {
vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId()));
}
if (StringUtils.isEmpty(vm.getVmtName())) {
VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid());
vm.setVmtName(t.getName());
}
if (vmDevices == null) {
VmDeviceUtils.setVmDevices(vm.getStaticData());
} else {
vm.getStaticData().setManagedDeviceMap(vmDevices);
}
if (disks == null) {
disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true);
disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true));
}
for (DiskImage image : disks) {
image.setStorageIds(null);
}
return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm));
}
/**
* Remove all the snapshots that belong to the given VM.
*
* @param vmId
* The ID of the VM.
* @return Set of memoryVolumes of the removed snapshots
*/
public Set<String> removeSnapshots(Guid vmId) {
final List<Snapshot> vmSnapshots = getSnapshotDao().getAll(vmId);
for (Snapshot snapshot : vmSnapshots) {
getSnapshotDao().remove(snapshot.getId());
}
return MemoryUtils.getMemoryVolumesFromSnapshots(vmSnapshots);
}
/**
* Remove all illegal disks which were associated with the given snapshot. This is done in order to be able to
* switch correctly between snapshots where illegal images might be present.
*
* @param vmId
* The vm ID the disk is associated with.
* @param snapshotId
* The ID of the snapshot for who to remove illegal images for.
*/
public void removeAllIllegalDisks(Guid snapshotId, Guid vmId) {
for (DiskImage diskImage : getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshotId)) {
if (diskImage.getImageStatus() == ImageStatus.ILLEGAL) {
ImagesHandler.removeDiskImage(diskImage, vmId);
}
}
}
/**
* Attempt to read the configuration that is stored in the snapshot, and restore the VM from it.<br>
* The NICs and Disks will be restored from the configuration (if available).<br>
* <br>
* <b>Note:</b>If the configuration is <code>null</code> or can't be decoded, then the VM configuration will remain
* as it was but the underlying storage would still have changed..
*
* @param snapshot
* The snapshot containing the configuration.
* @param version
* The compatibility version of the VM's cluster
* @param user
* The user that performs the action
*/
public void attempToRestoreVmConfigurationFromSnapshot(VM vm,
Snapshot snapshot,
Guid activeSnapshotId,
List<DiskImage> images,
CompensationContext compensationContext, Version version, DbUser user) {
boolean vmUpdatedFromConfiguration = false;
if (snapshot.getVmConfiguration() != null) {
vmUpdatedFromConfiguration = updateVmFromConfiguration(vm, snapshot.getVmConfiguration());
if (images != null) {
vmUpdatedFromConfiguration &= updateImagesByConfiguration(vm, images);
}
}
if (!vmUpdatedFromConfiguration) {
if (images == null) {
images = getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshot.getId());
}
vm.setImages(new ArrayList<>(images));
}
vm.setAppList(snapshot.getAppList());
getVmDynamicDao().update(vm.getDynamicData());
synchronizeDisksFromSnapshot(vm.getId(), snapshot.getId(), activeSnapshotId, vm.getImages(), vm.getName());
if (vmUpdatedFromConfiguration) {
getVmStaticDao().update(vm.getStaticData());
synchronizeNics(vm, compensationContext, user);
for (VmDevice vmDevice : getVmDeviceDao().getVmDeviceByVmId(vm.getId())) {
if (deviceCanBeRemoved(vmDevice)) {
getVmDeviceDao().remove(vmDevice.getId());
}
}
VmDeviceUtils.addImportedDevices(vm.getStaticData(), false);
}
}
private boolean updateImagesByConfiguration(VM vm, List<DiskImage> images) {
Map<Guid, VM> snapshotVmConfigurations = new HashMap<>();
ArrayList<DiskImage> imagesFromVmConf = new ArrayList<>();
for (DiskImage image : images) {
Guid vmSnapshotId = image.getVmSnapshotId();
VM vmFromConf = snapshotVmConfigurations.get(vmSnapshotId);
if (vmFromConf == null) {
vmFromConf = new VM();
Snapshot snapshot = getSnapshotDao().get(image.getVmSnapshotId());
if (!updateVmFromConfiguration(vmFromConf, snapshot.getVmConfiguration())) {
return false;
}
snapshotVmConfigurations.put(vmSnapshotId, vmFromConf);
}
for (DiskImage imageFromVmConf : vmFromConf.getImages()) {
if (imageFromVmConf.getId().equals(image.getId())) {
imageFromVmConf.setStorageIds(image.getStorageIds());
imagesFromVmConf.add(imageFromVmConf);
break;
}
}
}
vm.setImages(imagesFromVmConf);
return true;
}
/**
* @param vmDevice
* @return true if the device can be removed (disk which allows snapshot can be removed as it is part
* of the snapshot. Other disks shouldn't be removed as they are not part of the snapshot).
*/
private boolean deviceCanBeRemoved(VmDevice vmDevice) {
if (!vmDevice.getDevice().equals(VmDeviceType.DISK.getName()) || !vmDevice.getIsManaged()) {
return true;
}
return vmDevice.getSnapshotId() == null && getDiskDao().get(vmDevice.getDeviceId()).isAllowSnapshot();
}
/**
* Update the given VM with the (static) data that is contained in the configuration. The {@link VM#getImages()}
* will contain the images that were read from the configuration.
*
* @param vm
* The VM to update.
* @param configuration
* The configuration to update from.
* @return In case of a problem reading the configuration, <code>false</code>. Otherwise, <code>true</code>.
*/
public boolean updateVmFromConfiguration(VM vm, String configuration) {
try {
VmStatic oldVmStatic = vm.getStaticData();
VM tempVM = new VM();
ArrayList<DiskImage> images = new ArrayList<>();
ArrayList<VmNetworkInterface> interfaces = new ArrayList<>();
new OvfManager().ImportVm(configuration, tempVM, images, interfaces);
for (DiskImage diskImage : images) {
DiskImage dbImage = getDiskImageDao().getSnapshotById(diskImage.getImageId());
if (dbImage != null) {
diskImage.setStorageIds(dbImage.getStorageIds());
}
}
new VMStaticOvfLogHandler(tempVM.getStaticData()).resetDefaults(oldVmStatic);
vm.setStaticData(tempVM.getStaticData());
vm.setImages(images);
vm.setInterfaces(interfaces);
// These fields are not saved in the OVF, so get them from the current VM.
vm.setIsoPath(oldVmStatic.getIsoPath());
vm.setVdsGroupId(oldVmStatic.getVdsGroupId());
// The VM configuration does not hold the vds group Id.
// It is necessary to fetch the vm static from the Db, in order to get this information
VmStatic vmStaticFromDb = getVmStaticDao().get(vm.getId());
if (vmStaticFromDb != null) {
VDSGroup vdsGroup = getVdsGroupDao().get(vmStaticFromDb.getVdsGroupId());
if (vdsGroup != null) {
vm.setStoragePoolId(vdsGroup.getStoragePoolId());
vm.setVdsGroupCompatibilityVersion(vdsGroup.getCompatibilityVersion());
vm.setVdsGroupName(vdsGroup.getName());
vm.setVdsGroupCpuName(vdsGroup.getCpuName());
}
}
// if the required dedicated host is invalid -> use current VM dedicated host
if (!VmHandler.validateDedicatedVdsExistOnSameCluster(vm.getStaticData(), null)) {
vm.setDedicatedVmForVds(oldVmStatic.getDedicatedVmForVds());
}
validateQuota(vm);
return true;
} catch (OvfReaderException e) {
log.error("Failed to update VM from the configuration '{}': {}",
configuration,
e.getMessage());
log.debug("Exception", e);
return false;
}
}
/**
* Validate whether the quota supplied in snapshot configuration exists in<br>
* current setup, if not reset to null.<br>
*
* @param vm
* imported vm
*/
private void validateQuota(VM vm) {
if (vm.getQuotaId() != null) {
Quota quota = getQuotaDao().getById(vm.getQuotaId());
if (quota == null) {
vm.setQuotaId(null);
}
}
}
/**
* Synchronize the VM's {@link VmNetworkInterface}s with the ones from the snapshot.<br>
* All existing NICs will be deleted, and the ones from the snapshot re-added.<br>
* In case a MAC address is already in use, the user will be issued a warning in the audit log.
*
* @param nics
* The nics from snapshot.
* @param version
* The compatibility version of the VM's cluster
* @param user
* The user that performs the action
*/
protected void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user) {
VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(getMacPool(vm.getStoragePoolId()));
VnicProfileHelper vnicProfileHelper =
new VnicProfileHelper(vm.getVdsGroupId(),
vm.getStoragePoolId(),
vm.getVdsGroupCompatibilityVersion(),
AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES);
vmInterfaceManager.removeAll(vm.getId());
for (VmNetworkInterface vmInterface : vm.getInterfaces()) {
vmInterface.setVmId(vm.getId());
// These fields might not be saved in the OVF, so fill them with reasonable values.
if (vmInterface.getId() == null) {
vmInterface.setId(Guid.newGuid());
}
vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user);
vmInterfaceManager.add(vmInterface, compensationContext, true, vm.getOs(), vm.getVdsGroupCompatibilityVersion());
}
vnicProfileHelper.auditInvalidInterfaces(vm.getName());
}
private MacPoolManagerStrategy getMacPool(Guid storagePoolId) {
return MacPoolPerDcSingleton.getInstance().poolForDataCenter(storagePoolId);
}
/**
* Synchronize the VM's Disks with the images from the snapshot:<br>
* <ul>
* <li>Existing disks are updated.</li>
* <li>Disks that don't exist anymore get re-added.</li>
* <ul>
* <li>If the image is still in the DB, the disk is linked to it.</li>
* <li>If the image is not in the DB anymore, the disk will be marked as "broken"</li>
* </ul>
* </ul>
*
* @param vmId
* The VM ID is needed to re-add disks.
* @param snapshotId
* The snapshot ID is used to find only the VM disks at the time.
* @param disksFromSnapshot
* The disks that existed in the snapshot.
*/
protected void synchronizeDisksFromSnapshot(Guid vmId,
Guid snapshotId,
Guid activeSnapshotId,
List<DiskImage> disksFromSnapshot,
String vmName) {
List<Guid> diskIdsFromSnapshot = new ArrayList<>();
// Sync disks that exist or existed in the snapshot.
int count = 1;
for (DiskImage diskImage : disksFromSnapshot) {
diskIdsFromSnapshot.add(diskImage.getId());
if (getBaseDiskDao().exists(diskImage.getId())) {
getBaseDiskDao().update(diskImage);
} else {
// If can't find the image, insert it as illegal so that it can't be used and make the device unplugged.
if (getDiskImageDao().getSnapshotById(diskImage.getImageId()) == null) {
diskImage.setImageStatus(ImageStatus.ILLEGAL);
diskImage.setVmSnapshotId(activeSnapshotId);
ImagesHandler.addImage(diskImage, true, (diskImage.getStorageIds() == null) ? null :
new ImageStorageDomainMap(diskImage.getImageId(),
diskImage.getStorageIds().get(0),
diskImage.getQuotaId(),
diskImage.getDiskProfileId()));
}
ImagesHandler.addDiskToVm(diskImage, vmId);
}
diskImage.setDiskAlias(ImagesHandler.getSuggestedDiskAlias(diskImage, vmName, count));
count++;
}
removeDisksNotInSnapshot(vmId, diskIdsFromSnapshot);
}
/**
* Remove all the disks which are allowed to be snapshot but not exist in the snapshot and are not disk snapshots
* @param vmId - The vm id which is being snapshot.
* @param diskIdsFromSnapshot - An image group id list for images which are part of the VM.
*/
private void removeDisksNotInSnapshot(Guid vmId, List<Guid> diskIdsFromSnapshot) {
for (VmDevice vmDevice : getVmDeviceDao().getVmDeviceByVmIdTypeAndDevice(
vmId, VmDeviceGeneralType.DISK, VmDeviceType.DISK.getName())) {
if (!diskIdsFromSnapshot.contains(vmDevice.getDeviceId()) && vmDevice.getSnapshotId() == null) {
Disk disk = getDiskDao().get(vmDevice.getDeviceId());
if (disk != null && disk.isAllowSnapshot()) {
getBaseDiskDao().remove(vmDevice.getDeviceId());
getVmDeviceDao().remove(vmDevice.getId());
}
}
}
}
protected VmDeviceDAO getVmDeviceDao() {
return DbFacade.getInstance().getVmDeviceDao();
}
protected BaseDiskDao getBaseDiskDao() {
return DbFacade.getInstance().getBaseDiskDao();
}
protected SnapshotDao getSnapshotDao() {
return DbFacade.getInstance().getSnapshotDao();
}
protected VmDynamicDAO getVmDynamicDao() {
return DbFacade.getInstance().getVmDynamicDao();
}
protected VmStaticDAO getVmStaticDao() {
return DbFacade.getInstance().getVmStaticDao();
}
protected DiskImageDAO getDiskImageDao() {
return DbFacade.getInstance().getDiskImageDao();
}
protected DiskDao getDiskDao() {
return DbFacade.getInstance().getDiskDao();
}
protected VdsGroupDAO getVdsGroupDao() {
return DbFacade.getInstance().getVdsGroupDao();
}
protected VmTemplateDAO getVmTemplateDao() {
return DbFacade.getInstance().getVmTemplateDao();
}
protected VmNetworkInterfaceDao getVmNetworkInterfaceDao() {
return DbFacade.getInstance().getVmNetworkInterfaceDao();
}
protected QuotaDAO getQuotaDao() {
return DbFacade.getInstance().getQuotaDao();
}
}
| backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/snapshots/SnapshotsManager.java | package org.ovirt.engine.core.bll.snapshots;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.VmHandler;
import org.ovirt.engine.core.bll.context.CompensationContext;
import org.ovirt.engine.core.bll.memory.MemoryUtils;
import org.ovirt.engine.core.bll.network.VmInterfaceManager;
import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolManagerStrategy;
import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolPerDcSingleton;
import org.ovirt.engine.core.bll.network.vm.VnicProfileHelper;
import org.ovirt.engine.core.bll.utils.ClusterUtils;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.aaa.DbUser;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.ImageStorageDomainMap;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.BaseDiskDao;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.DiskImageDAO;
import org.ovirt.engine.core.dao.QuotaDAO;
import org.ovirt.engine.core.dao.SnapshotDao;
import org.ovirt.engine.core.dao.VdsGroupDAO;
import org.ovirt.engine.core.dao.VmDeviceDAO;
import org.ovirt.engine.core.dao.VmDynamicDAO;
import org.ovirt.engine.core.dao.VmStaticDAO;
import org.ovirt.engine.core.dao.VmTemplateDAO;
import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao;
import org.ovirt.engine.core.utils.ovf.OvfManager;
import org.ovirt.engine.core.utils.ovf.OvfReaderException;
import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link Snapshot} manager is used to easily add/update/remove snapshots.
*/
public class SnapshotsManager {
private final static Logger log = LoggerFactory.getLogger(SnapshotsManager.class);
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
"",
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the created snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
snapshotStatus,
"",
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @see #addActiveSnapshot(Guid, VM, SnapshotStatus, CompensationContext)
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param memoryVolume
* The memory state for the created snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
String memoryVolume,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
memoryVolume,
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created in status {@link SnapshotStatus#OK} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param memoryVolume
* The memory state for the created snapshot
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the newly created snapshot
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
SnapshotStatus.OK,
memoryVolume,
disks,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created with the given status {@link SnapshotStatus}.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the snapshot
* @param compensationContext
* Context for saving compensation details.
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
String memoryVolume,
final CompensationContext compensationContext) {
return addActiveSnapshot(snapshotId,
vm,
snapshotStatus,
memoryVolume,
null,
compensationContext);
}
/**
* Save an active snapshot for the VM, without saving the configuration.<br>
* The snapshot is created with the given status {@link SnapshotStatus}.
*
* @param snapshotId
* The ID for the snapshot.
* @param vm
* The VM to save the snapshot for.
* @param snapshotStatus
* The initial status of the snapshot
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
*/
public Snapshot addActiveSnapshot(Guid snapshotId,
VM vm,
SnapshotStatus snapshotStatus,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId,
"Active VM",
snapshotStatus,
SnapshotType.ACTIVE,
vm,
false,
memoryVolume,
disks,
compensationContext);
}
/**
* Add a new snapshot, saving it to the DB (with compensation). The VM's current configuration (including Disks &
* NICs) will be saved in the snapshot.<br>
* The snapshot is created in status {@link SnapshotStatus#LOCKED} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param description
* The snapshot description.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to save in configuration.
* @param memoryVolume
* the volume in which the snapshot's memory is stored
* @param compensationContext
* Context for saving compensation details.
* @return the added snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotType snapshotType,
VM vm,
String memoryVolume,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId, description, SnapshotStatus.LOCKED,
snapshotType, vm, true, memoryVolume, null, compensationContext);
}
/**
* Add a new snapshot, saving it to the DB (with compensation). The VM's current configuration (including Disks &
* NICs) will be saved in the snapshot.<br>
* The snapshot is created in status {@link SnapshotStatus#LOCKED} by default.
*
* @param snapshotId
* The ID for the snapshot.
* @param description
* The snapshot description.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to save in configuration.
* @param memoryVolume
* the volume in which the snapshot's memory is stored
* @param disks
* The disks contained in the snapshot
* @param compensationContext
* Context for saving compensation details.
* @return the added snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotType snapshotType,
VM vm,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId, description, SnapshotStatus.LOCKED,
snapshotType, vm, true, memoryVolume, disks, compensationContext);
}
/**addSnapshot
* Save snapshot to DB with compensation data.
*
* @param snapshotId
* The snapshot ID.
* @param description
* The snapshot description.
* @param snapshotStatus
* The snapshot status.
* @param snapshotType
* The snapshot type.
* @param vm
* The VM to link to & save configuration for (if necessary).
* @param saveVmConfiguration
* Should VM configuration be generated and saved?
* @param compensationContext
* In case compensation is needed.
* @return the saved snapshot
*/
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotStatus snapshotStatus,
SnapshotType snapshotType,
VM vm,
boolean saveVmConfiguration,
String memoryVolume,
List<DiskImage> disks,
final CompensationContext compensationContext) {
return addSnapshot(snapshotId,
description,
snapshotStatus,
snapshotType,
vm,
saveVmConfiguration,
memoryVolume,
disks,
null,
compensationContext);
}
public Snapshot addSnapshot(Guid snapshotId,
String description,
SnapshotStatus snapshotStatus,
SnapshotType snapshotType,
VM vm,
boolean saveVmConfiguration,
String memoryVolume,
List<DiskImage> disks,
Map<Guid, VmDevice> vmDevices,
final CompensationContext compensationContext) {
final Snapshot snapshot = new Snapshot(snapshotId,
snapshotStatus,
vm.getId(),
saveVmConfiguration ? generateVmConfiguration(vm, disks, vmDevices) : null,
snapshotType,
description,
new Date(),
vm.getAppList(),
memoryVolume);
getSnapshotDao().save(snapshot);
compensationContext.snapshotNewEntity(snapshot);
return snapshot;
}
/**
* Generate a string containing the given VM's configuration.
*
* @param vm
* The VM to generate configuration from.
* @return A String containing the VM configuration.
*/
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) {
if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) {
vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId()));
}
if (StringUtils.isEmpty(vm.getVmtName())) {
VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid());
vm.setVmtName(t.getName());
}
if (vmDevices == null) {
VmDeviceUtils.setVmDevices(vm.getStaticData());
} else {
vm.getStaticData().setManagedDeviceMap(vmDevices);
}
if (disks == null) {
disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true);
}
for (DiskImage image : disks) {
image.setStorageIds(null);
}
return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm));
}
/**
* Remove all the snapshots that belong to the given VM.
*
* @param vmId
* The ID of the VM.
* @return Set of memoryVolumes of the removed snapshots
*/
public Set<String> removeSnapshots(Guid vmId) {
final List<Snapshot> vmSnapshots = getSnapshotDao().getAll(vmId);
for (Snapshot snapshot : vmSnapshots) {
getSnapshotDao().remove(snapshot.getId());
}
return MemoryUtils.getMemoryVolumesFromSnapshots(vmSnapshots);
}
/**
* Remove all illegal disks which were associated with the given snapshot. This is done in order to be able to
* switch correctly between snapshots where illegal images might be present.
*
* @param vmId
* The vm ID the disk is associated with.
* @param snapshotId
* The ID of the snapshot for who to remove illegal images for.
*/
public void removeAllIllegalDisks(Guid snapshotId, Guid vmId) {
for (DiskImage diskImage : getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshotId)) {
if (diskImage.getImageStatus() == ImageStatus.ILLEGAL) {
ImagesHandler.removeDiskImage(diskImage, vmId);
}
}
}
/**
* Attempt to read the configuration that is stored in the snapshot, and restore the VM from it.<br>
* The NICs and Disks will be restored from the configuration (if available).<br>
* <br>
* <b>Note:</b>If the configuration is <code>null</code> or can't be decoded, then the VM configuration will remain
* as it was but the underlying storage would still have changed..
*
* @param snapshot
* The snapshot containing the configuration.
* @param version
* The compatibility version of the VM's cluster
* @param user
* The user that performs the action
*/
public void attempToRestoreVmConfigurationFromSnapshot(VM vm,
Snapshot snapshot,
Guid activeSnapshotId,
List<DiskImage> images,
CompensationContext compensationContext, Version version, DbUser user) {
boolean vmUpdatedFromConfiguration = false;
if (snapshot.getVmConfiguration() != null) {
vmUpdatedFromConfiguration = updateVmFromConfiguration(vm, snapshot.getVmConfiguration());
if (images != null) {
vmUpdatedFromConfiguration &= updateImagesByConfiguration(vm, images);
}
}
if (!vmUpdatedFromConfiguration) {
if (images == null) {
images = getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshot.getId());
}
vm.setImages(new ArrayList<>(images));
}
vm.setAppList(snapshot.getAppList());
getVmDynamicDao().update(vm.getDynamicData());
synchronizeDisksFromSnapshot(vm.getId(), snapshot.getId(), activeSnapshotId, vm.getImages(), vm.getName());
if (vmUpdatedFromConfiguration) {
getVmStaticDao().update(vm.getStaticData());
synchronizeNics(vm, compensationContext, user);
for (VmDevice vmDevice : getVmDeviceDao().getVmDeviceByVmId(vm.getId())) {
if (deviceCanBeRemoved(vmDevice)) {
getVmDeviceDao().remove(vmDevice.getId());
}
}
VmDeviceUtils.addImportedDevices(vm.getStaticData(), false);
}
}
private boolean updateImagesByConfiguration(VM vm, List<DiskImage> images) {
Map<Guid, VM> snapshotVmConfigurations = new HashMap<>();
ArrayList<DiskImage> imagesFromVmConf = new ArrayList<>();
for (DiskImage image : images) {
Guid vmSnapshotId = image.getVmSnapshotId();
VM vmFromConf = snapshotVmConfigurations.get(vmSnapshotId);
if (vmFromConf == null) {
vmFromConf = new VM();
Snapshot snapshot = getSnapshotDao().get(image.getVmSnapshotId());
if (!updateVmFromConfiguration(vmFromConf, snapshot.getVmConfiguration())) {
return false;
}
snapshotVmConfigurations.put(vmSnapshotId, vmFromConf);
}
for (DiskImage imageFromVmConf : vmFromConf.getImages()) {
if (imageFromVmConf.getId().equals(image.getId())) {
imageFromVmConf.setStorageIds(image.getStorageIds());
imagesFromVmConf.add(imageFromVmConf);
break;
}
}
}
vm.setImages(imagesFromVmConf);
return true;
}
/**
* @param vmDevice
* @return true if the device can be removed (disk which allows snapshot can be removed as it is part
* of the snapshot. Other disks shouldn't be removed as they are not part of the snapshot).
*/
private boolean deviceCanBeRemoved(VmDevice vmDevice) {
if (!vmDevice.getDevice().equals(VmDeviceType.DISK.getName()) || !vmDevice.getIsManaged()) {
return true;
}
return vmDevice.getSnapshotId() == null && getDiskDao().get(vmDevice.getDeviceId()).isAllowSnapshot();
}
/**
* Update the given VM with the (static) data that is contained in the configuration. The {@link VM#getImages()}
* will contain the images that were read from the configuration.
*
* @param vm
* The VM to update.
* @param configuration
* The configuration to update from.
* @return In case of a problem reading the configuration, <code>false</code>. Otherwise, <code>true</code>.
*/
public boolean updateVmFromConfiguration(VM vm, String configuration) {
try {
VmStatic oldVmStatic = vm.getStaticData();
VM tempVM = new VM();
ArrayList<DiskImage> images = new ArrayList<>();
ArrayList<VmNetworkInterface> interfaces = new ArrayList<>();
new OvfManager().ImportVm(configuration, tempVM, images, interfaces);
for (DiskImage diskImage : images) {
DiskImage dbImage = getDiskImageDao().getSnapshotById(diskImage.getImageId());
if (dbImage != null) {
diskImage.setStorageIds(dbImage.getStorageIds());
}
}
new VMStaticOvfLogHandler(tempVM.getStaticData()).resetDefaults(oldVmStatic);
vm.setStaticData(tempVM.getStaticData());
vm.setImages(images);
vm.setInterfaces(interfaces);
// These fields are not saved in the OVF, so get them from the current VM.
vm.setIsoPath(oldVmStatic.getIsoPath());
vm.setVdsGroupId(oldVmStatic.getVdsGroupId());
// The VM configuration does not hold the vds group Id.
// It is necessary to fetch the vm static from the Db, in order to get this information
VmStatic vmStaticFromDb = getVmStaticDao().get(vm.getId());
if (vmStaticFromDb != null) {
VDSGroup vdsGroup = getVdsGroupDao().get(vmStaticFromDb.getVdsGroupId());
if (vdsGroup != null) {
vm.setStoragePoolId(vdsGroup.getStoragePoolId());
vm.setVdsGroupCompatibilityVersion(vdsGroup.getCompatibilityVersion());
vm.setVdsGroupName(vdsGroup.getName());
vm.setVdsGroupCpuName(vdsGroup.getCpuName());
}
}
// if the required dedicated host is invalid -> use current VM dedicated host
if (!VmHandler.validateDedicatedVdsExistOnSameCluster(vm.getStaticData(), null)) {
vm.setDedicatedVmForVds(oldVmStatic.getDedicatedVmForVds());
}
validateQuota(vm);
return true;
} catch (OvfReaderException e) {
log.error("Failed to update VM from the configuration '{}': {}",
configuration,
e.getMessage());
log.debug("Exception", e);
return false;
}
}
/**
* Validate whether the quota supplied in snapshot configuration exists in<br>
* current setup, if not reset to null.<br>
*
* @param vm
* imported vm
*/
private void validateQuota(VM vm) {
if (vm.getQuotaId() != null) {
Quota quota = getQuotaDao().getById(vm.getQuotaId());
if (quota == null) {
vm.setQuotaId(null);
}
}
}
/**
* Synchronize the VM's {@link VmNetworkInterface}s with the ones from the snapshot.<br>
* All existing NICs will be deleted, and the ones from the snapshot re-added.<br>
* In case a MAC address is already in use, the user will be issued a warning in the audit log.
*
* @param nics
* The nics from snapshot.
* @param version
* The compatibility version of the VM's cluster
* @param user
* The user that performs the action
*/
protected void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user) {
VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(getMacPool(vm.getStoragePoolId()));
VnicProfileHelper vnicProfileHelper =
new VnicProfileHelper(vm.getVdsGroupId(),
vm.getStoragePoolId(),
vm.getVdsGroupCompatibilityVersion(),
AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES);
vmInterfaceManager.removeAll(vm.getId());
for (VmNetworkInterface vmInterface : vm.getInterfaces()) {
vmInterface.setVmId(vm.getId());
// These fields might not be saved in the OVF, so fill them with reasonable values.
if (vmInterface.getId() == null) {
vmInterface.setId(Guid.newGuid());
}
vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user);
vmInterfaceManager.add(vmInterface, compensationContext, true, vm.getOs(), vm.getVdsGroupCompatibilityVersion());
}
vnicProfileHelper.auditInvalidInterfaces(vm.getName());
}
private MacPoolManagerStrategy getMacPool(Guid storagePoolId) {
return MacPoolPerDcSingleton.getInstance().poolForDataCenter(storagePoolId);
}
/**
* Synchronize the VM's Disks with the images from the snapshot:<br>
* <ul>
* <li>Existing disks are updated.</li>
* <li>Disks that don't exist anymore get re-added.</li>
* <ul>
* <li>If the image is still in the DB, the disk is linked to it.</li>
* <li>If the image is not in the DB anymore, the disk will be marked as "broken"</li>
* </ul>
* </ul>
*
* @param vmId
* The VM ID is needed to re-add disks.
* @param snapshotId
* The snapshot ID is used to find only the VM disks at the time.
* @param disksFromSnapshot
* The disks that existed in the snapshot.
*/
protected void synchronizeDisksFromSnapshot(Guid vmId,
Guid snapshotId,
Guid activeSnapshotId,
List<DiskImage> disksFromSnapshot,
String vmName) {
List<Guid> diskIdsFromSnapshot = new ArrayList<>();
// Sync disks that exist or existed in the snapshot.
int count = 1;
for (DiskImage diskImage : disksFromSnapshot) {
diskIdsFromSnapshot.add(diskImage.getId());
if (getBaseDiskDao().exists(diskImage.getId())) {
getBaseDiskDao().update(diskImage);
} else {
// If can't find the image, insert it as illegal so that it can't be used and make the device unplugged.
if (getDiskImageDao().getSnapshotById(diskImage.getImageId()) == null) {
diskImage.setImageStatus(ImageStatus.ILLEGAL);
diskImage.setVmSnapshotId(activeSnapshotId);
ImagesHandler.addImage(diskImage, true, (diskImage.getStorageIds() == null) ? null :
new ImageStorageDomainMap(diskImage.getImageId(),
diskImage.getStorageIds().get(0),
diskImage.getQuotaId(),
diskImage.getDiskProfileId()));
}
ImagesHandler.addDiskToVm(diskImage, vmId);
}
diskImage.setDiskAlias(ImagesHandler.getSuggestedDiskAlias(diskImage, vmName, count));
count++;
}
removeDisksNotInSnapshot(vmId, diskIdsFromSnapshot);
}
/**
* Remove all the disks which are allowed to be snapshot but not exist in the snapshot and are not disk snapshots
* @param vmId - The vm id which is being snapshot.
* @param diskIdsFromSnapshot - An image group id list for images which are part of the VM.
*/
private void removeDisksNotInSnapshot(Guid vmId, List<Guid> diskIdsFromSnapshot) {
for (VmDevice vmDevice : getVmDeviceDao().getVmDeviceByVmIdTypeAndDevice(
vmId, VmDeviceGeneralType.DISK, VmDeviceType.DISK.getName())) {
if (!diskIdsFromSnapshot.contains(vmDevice.getDeviceId()) && vmDevice.getSnapshotId() == null) {
Disk disk = getDiskDao().get(vmDevice.getDeviceId());
if (disk != null && disk.isAllowSnapshot()) {
getBaseDiskDao().remove(vmDevice.getDeviceId());
getVmDeviceDao().remove(vmDevice.getId());
}
}
}
}
protected VmDeviceDAO getVmDeviceDao() {
return DbFacade.getInstance().getVmDeviceDao();
}
protected BaseDiskDao getBaseDiskDao() {
return DbFacade.getInstance().getBaseDiskDao();
}
protected SnapshotDao getSnapshotDao() {
return DbFacade.getInstance().getSnapshotDao();
}
protected VmDynamicDAO getVmDynamicDao() {
return DbFacade.getInstance().getVmDynamicDao();
}
protected VmStaticDAO getVmStaticDao() {
return DbFacade.getInstance().getVmStaticDao();
}
protected DiskImageDAO getDiskImageDao() {
return DbFacade.getInstance().getDiskImageDao();
}
protected DiskDao getDiskDao() {
return DbFacade.getInstance().getDiskDao();
}
protected VdsGroupDAO getVdsGroupDao() {
return DbFacade.getInstance().getVdsGroupDao();
}
protected VmTemplateDAO getVmTemplateDao() {
return DbFacade.getInstance().getVmTemplateDao();
}
protected VmNetworkInterfaceDao getVmNetworkInterfaceDao() {
return DbFacade.getInstance().getVmNetworkInterfaceDao();
}
protected QuotaDAO getQuotaDao() {
return DbFacade.getInstance().getQuotaDao();
}
}
| core: Add Cinder disks to snapshot OVF.
Add also Cinder disks to a list of disks which are initialized with
empty storage domain id while adding a snapshot, so Cinder disks will also
get updated with the accurate Storage Domain id in case of a move operation.
Change-Id: Icaf67979493885ef2f53ac27afd8383942d242ca
Bug-Url: https://bugzilla.redhat.com/1185826
Signed-off-by: Maor Lipchuk <[email protected]>
| backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/snapshots/SnapshotsManager.java | core: Add Cinder disks to snapshot OVF. | <ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/snapshots/SnapshotsManager.java
<ide>
<ide> if (disks == null) {
<ide> disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true);
<add> disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true));
<ide> }
<ide> for (DiskImage image : disks) {
<ide> image.setStorageIds(null); |
|
Java | apache-2.0 | 637d107d1b3d4952883333f27b101226c95e21ef | 0 | apache/commons-digester,apache/commons-digester,callMeDimit/commons-digester,mohanaraosv/commons-digester,callMeDimit/commons-digester,mohanaraosv/commons-digester,mohanaraosv/commons-digester,apache/commons-digester,callMeDimit/commons-digester | package org.apache.commons.digester3.xmlrules;
/*
* 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 static java.util.Collections.unmodifiableSet;
import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.AbstractRulesModule;
import org.xml.sax.InputSource;
/**
* {@link org.apache.commons.digester3.binder.RulesModule} implementation that allows loading rules from
* XML files.
*
* @since 3.0
*/
public abstract class FromXmlRulesModule
extends AbstractRulesModule
{
private static final String DIGESTER_PUBLIC_ID = "-//Apache Commons //DTD digester-rules XML V1.0//EN";
private static final String DIGESTER_DTD_PATH = "digester-rules.dtd";
private final URL xmlRulesDtdUrl = FromXmlRulesModule.class.getResource( DIGESTER_DTD_PATH );
private final Set<String> systemIds = new HashSet<String>();
private String rootPath;
/**
* {@inheritDoc}
*/
@Override
protected void configure()
{
if ( !systemIds.isEmpty() )
{
throw new IllegalStateException( "Re-entry is not allowed." );
}
try
{
loadRules();
}
finally
{
systemIds.clear();
}
}
/**
*
*/
protected abstract void loadRules();
/**
* Reads the XML rules from the given {@code org.xml.sax.InputSource}.
*
* @param inputSource The {@code org.xml.sax.InputSource} where reading the XML rules from.
*/
protected final void loadXMLRules( InputSource inputSource )
{
if ( inputSource == null )
{
throw new IllegalArgumentException( "Argument 'inputSource' must be not null" );
}
String systemId = inputSource.getSystemId();
if ( systemId != null && !systemIds.add( systemId ) )
{
addError( "XML rules file '%s' already bound", systemId );
}
XmlRulesModule xmlRulesModule = new XmlRulesModule( new NameSpaceURIRulesBinder( rulesBinder() ),
getSystemIds(), rootPath );
Digester digester = newLoader( xmlRulesModule )
.register( DIGESTER_PUBLIC_ID, xmlRulesDtdUrl.toString() )
.setXIncludeAware( true )
.setValidating( true )
.newDigester();
try
{
digester.parse( inputSource );
}
catch ( Exception e )
{
addError( "Impossible to load XML defined in the InputSource '%s': %s", inputSource.getSystemId(),
e.getMessage() );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.InputStream}.
*
* @param input The {@code java.io.InputStream} where reading the XML rules from.
*/
protected final void loadXMLRules( InputStream input )
{
if ( input == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
loadXMLRules( new InputSource( input ) );
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.Reader}.
*
* @param reader The {@code java.io.Reader} where reading the XML rules from.
*/
protected final void loadXMLRules( Reader reader )
{
if ( reader == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
loadXMLRules( new InputSource( reader ) );
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.File}.
*
* @param file The {@code java.io.File} where reading the XML rules from.
*/
protected final void loadXMLRules( File file )
{
if ( file == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
try
{
loadXMLRules( file.toURI().toURL() );
}
catch ( MalformedURLException e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a URI in String representation.
*
* @param uri The URI in String representation where reading the XML rules from.
*/
protected final void loadXMLRules( String uri )
{
if ( uri == null )
{
throw new IllegalArgumentException( "Argument 'uri' must be not null" );
}
try
{
loadXMLRules( new URL( uri ) );
}
catch ( MalformedURLException e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.net.URL}.
*
* @param url The {@code java.net.URL} where reading the XML rules from.
*/
protected final void loadXMLRules( URL url )
{
if ( url == null )
{
throw new IllegalArgumentException( "Argument 'url' must be not null" );
}
try
{
URLConnection connection = url.openConnection();
connection.setUseCaches( false );
InputStream stream = connection.getInputStream();
InputSource source = new InputSource( stream );
source.setSystemId( url.toExternalForm() );
loadXMLRules( source );
}
catch ( Exception e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given an XML document in textual form.
*
* @param xmlText The XML document in textual form where reading the XML rules from.
*/
protected final void loadXMLRulesFromText( String xmlText )
{
if ( xmlText == null )
{
throw new IllegalArgumentException( "Argument 'xmlText' must be not null" );
}
loadXMLRules( new StringReader( xmlText ) );
}
/**
* Set the root path (will be used when composing modules).
*
* @param rootPath The root path
*/
protected final void useRootPath( String rootPath )
{
this.rootPath = rootPath;
}
/**
* Returns the XML source SystemIds load by this module.
*
* @return The XML source SystemIds load by this module
*/
public final Set<String> getSystemIds()
{
return unmodifiableSet( systemIds );
}
}
| core/src/main/java/org/apache/commons/digester3/xmlrules/FromXmlRulesModule.java | package org.apache.commons.digester3.xmlrules;
/*
* 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 static java.util.Collections.unmodifiableSet;
import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.AbstractRulesModule;
import org.xml.sax.InputSource;
/**
* {@link org.apache.commons.digester3.binder.RulesModule} implementation that allows loading rules from
* XML files.
*
* @since 3.0
*/
public abstract class FromXmlRulesModule
extends AbstractRulesModule
{
private static final String DIGESTER_PUBLIC_ID = "-//Apache Commons //DTD digester-rules XML V1.0//EN";
private static final String DIGESTER_DTD_PATH = "digester-rules.dtd";
private final URL xmlRulesDtdUrl = FromXmlRulesModule.class.getResource( DIGESTER_DTD_PATH );
private final ThreadLocal<Set<String>> systemIds = new ThreadLocal<Set<String>>();
private String rootPath;
/**
* {@inheritDoc}
*/
@Override
protected void configure()
{
if ( systemIds.get() != null )
{
throw new IllegalStateException( "Re-entry is not allowed." );
}
systemIds.set( new HashSet<String>() );
try
{
loadRules();
}
finally
{
systemIds.remove();
}
}
/**
*
*/
protected abstract void loadRules();
/**
* Reads the XML rules from the given {@code org.xml.sax.InputSource}.
*
* @param inputSource The {@code org.xml.sax.InputSource} where reading the XML rules from.
*/
protected final void loadXMLRules( InputSource inputSource )
{
if ( inputSource == null )
{
throw new IllegalArgumentException( "Argument 'inputSource' must be not null" );
}
String systemId = inputSource.getSystemId();
if ( systemId != null && !systemIds.get().add( systemId ) )
{
addError( "XML rules file '%s' already bound", systemId );
}
XmlRulesModule xmlRulesModule = new XmlRulesModule( new NameSpaceURIRulesBinder( rulesBinder() ),
getSystemIds(), rootPath );
Digester digester = newLoader( xmlRulesModule )
.register( DIGESTER_PUBLIC_ID, xmlRulesDtdUrl.toString() )
.setXIncludeAware( true )
.setValidating( true )
.newDigester();
try
{
digester.parse( inputSource );
}
catch ( Exception e )
{
addError( "Impossible to load XML defined in the InputSource '%s': %s", inputSource.getSystemId(),
e.getMessage() );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.InputStream}.
*
* @param input The {@code java.io.InputStream} where reading the XML rules from.
*/
protected final void loadXMLRules( InputStream input )
{
if ( input == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
loadXMLRules( new InputSource( input ) );
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.Reader}.
*
* @param reader The {@code java.io.Reader} where reading the XML rules from.
*/
protected final void loadXMLRules( Reader reader )
{
if ( reader == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
loadXMLRules( new InputSource( reader ) );
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.io.File}.
*
* @param file The {@code java.io.File} where reading the XML rules from.
*/
protected final void loadXMLRules( File file )
{
if ( file == null )
{
throw new IllegalArgumentException( "Argument 'input' must be not null" );
}
try
{
loadXMLRules( file.toURI().toURL() );
}
catch ( MalformedURLException e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a URI in String representation.
*
* @param uri The URI in String representation where reading the XML rules from.
*/
protected final void loadXMLRules( String uri )
{
if ( uri == null )
{
throw new IllegalArgumentException( "Argument 'uri' must be not null" );
}
try
{
loadXMLRules( new URL( uri ) );
}
catch ( MalformedURLException e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given a {@code java.net.URL}.
*
* @param url The {@code java.net.URL} where reading the XML rules from.
*/
protected final void loadXMLRules( URL url )
{
if ( url == null )
{
throw new IllegalArgumentException( "Argument 'url' must be not null" );
}
try
{
URLConnection connection = url.openConnection();
connection.setUseCaches( false );
InputStream stream = connection.getInputStream();
InputSource source = new InputSource( stream );
source.setSystemId( url.toExternalForm() );
loadXMLRules( source );
}
catch ( Exception e )
{
rulesBinder().addError( e );
}
}
/**
* Opens a new {@code org.xml.sax.InputSource} given an XML document in textual form.
*
* @param xmlText The XML document in textual form where reading the XML rules from.
*/
protected final void loadXMLRulesFromText( String xmlText )
{
if ( xmlText == null )
{
throw new IllegalArgumentException( "Argument 'xmlText' must be not null" );
}
loadXMLRules( new StringReader( xmlText ) );
}
/**
* Set the root path (will be used when composing modules).
*
* @param rootPath The root path
*/
protected final void useRootPath( String rootPath )
{
this.rootPath = rootPath;
}
/**
* Returns the XML source SystemIds load by this module.
*
* @return The XML source SystemIds load by this module
*/
public final Set<String> getSystemIds()
{
return unmodifiableSet( systemIds.get() );
}
}
| no needs to store system ids to a ThreadLocal, modules not invoked in lazy-loading way anymore
git-svn-id: 871f264856ddff118359d15337bbbf32ea57c748@1301817 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/commons/digester3/xmlrules/FromXmlRulesModule.java | no needs to store system ids to a ThreadLocal, modules not invoked in lazy-loading way anymore | <ide><path>ore/src/main/java/org/apache/commons/digester3/xmlrules/FromXmlRulesModule.java
<ide>
<ide> private final URL xmlRulesDtdUrl = FromXmlRulesModule.class.getResource( DIGESTER_DTD_PATH );
<ide>
<del> private final ThreadLocal<Set<String>> systemIds = new ThreadLocal<Set<String>>();
<add> private final Set<String> systemIds = new HashSet<String>();
<ide>
<ide> private String rootPath;
<ide>
<ide> @Override
<ide> protected void configure()
<ide> {
<del> if ( systemIds.get() != null )
<add> if ( !systemIds.isEmpty() )
<ide> {
<ide> throw new IllegalStateException( "Re-entry is not allowed." );
<ide> }
<ide>
<del> systemIds.set( new HashSet<String>() );
<ide> try
<ide> {
<ide> loadRules();
<ide> }
<ide> finally
<ide> {
<del> systemIds.remove();
<add> systemIds.clear();
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> String systemId = inputSource.getSystemId();
<del> if ( systemId != null && !systemIds.get().add( systemId ) )
<add> if ( systemId != null && !systemIds.add( systemId ) )
<ide> {
<ide> addError( "XML rules file '%s' already bound", systemId );
<ide> }
<ide> */
<ide> public final Set<String> getSystemIds()
<ide> {
<del> return unmodifiableSet( systemIds.get() );
<add> return unmodifiableSet( systemIds );
<ide> }
<ide>
<ide> } |
|
Java | epl-1.0 | f46a94753f050e21a6977b3a780a3df318621d8b | 0 | blizzy78/egit,SmithAndr/egit,paulvi/egit,paulvi/egit,collaborative-modeling/egit,collaborative-modeling/egit,SmithAndr/egit,wdliu/egit,wdliu/egit | /*******************************************************************************
* Copyright (C) 2007, Dave Watson <[email protected]>
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2008, Robin Rosenberg <[email protected]>
* Copyright (C) 2007, Shawn O. Pearce <[email protected]>
* Copyright (C) 2011, Mathias Kinzler <[email protected]>
* Copyright (C) 2012, Daniel Megert <[email protected]>
* Copyright (C) 2012, 2013 Robin Stocker <[email protected]>
* Copyright (C) 2012, IBM Corporation (Markus Keller <[email protected]>)
* Copyright (C) 2013, François Rey <eclipse.org_@_francois_._rey_._name>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.dialogs;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.egit.core.AdaptableFileTreeIterator;
import org.eclipse.egit.core.internal.util.ResourceUtil;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.egit.ui.UIUtils;
import org.eclipse.egit.ui.internal.CachedCheckboxTreeViewer;
import org.eclipse.egit.ui.internal.CompareUtils;
import org.eclipse.egit.ui.internal.FilteredCheckboxTree;
import org.eclipse.egit.ui.internal.UIIcons;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.commit.CommitHelper;
import org.eclipse.egit.ui.internal.commit.CommitMessageHistory;
import org.eclipse.egit.ui.internal.commit.CommitProposalProcessor;
import org.eclipse.egit.ui.internal.decorators.IProblemDecoratable;
import org.eclipse.egit.ui.internal.decorators.ProblemLabelDecorator;
import org.eclipse.egit.ui.internal.dialogs.CommitItem.Status;
import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponent.CommitStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider;
import org.eclipse.jface.viewers.DecorationOverlayIcon;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.IndexDiff;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.progress.WorkbenchJob;
/**
* Dialog is shown to user when they request to commit files. Changes in the
* selected portion of the tree are shown.
*/
public class CommitDialog extends TitleAreaDialog {
private static IPreferenceStore getPreferenceStore() {
return org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore();
}
static class CommitFileContentProvider extends BaseWorkbenchContentProvider {
@Override
public Object[] getElements(Object element) {
if (element instanceof Object[])
return (Object[]) element;
if (element instanceof Collection)
return ((Collection) element).toArray();
return new Object[0];
}
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
return false;
}
}
static class CommitStatusLabelProvider extends BaseLabelProvider implements
IStyledLabelProvider {
private Image DEFAULT = PlatformUI.getWorkbench().getSharedImages()
.getImage(ISharedImages.IMG_OBJ_FILE);
private ResourceManager resourceManager = new LocalResourceManager(
JFaceResources.getResources());
private final Image SUBMODULE = UIIcons.REPOSITORY.createImage();
private Image getEditorImage(CommitItem item) {
if (!item.submodule) {
Image image = DEFAULT;
String name = new Path(item.path).lastSegment();
if (name != null) {
ImageDescriptor descriptor = PlatformUI.getWorkbench()
.getEditorRegistry().getImageDescriptor(name);
image = (Image) this.resourceManager.get(descriptor);
}
return image;
} else
return SUBMODULE;
}
private Image getDecoratedImage(Image base, ImageDescriptor decorator) {
DecorationOverlayIcon decorated = new DecorationOverlayIcon(base,
decorator, IDecoration.BOTTOM_RIGHT);
return (Image) this.resourceManager.get(decorated);
}
public StyledString getStyledText(Object element) {
return new StyledString();
}
public Image getImage(Object element) {
CommitItem item = (CommitItem) element;
ImageDescriptor decorator = null;
switch (item.status) {
case UNTRACKED:
decorator = UIIcons.OVR_UNTRACKED;
break;
case ADDED:
case ADDED_INDEX_DIFF:
decorator = UIIcons.OVR_STAGED_ADD;
break;
case REMOVED:
case REMOVED_NOT_STAGED:
case REMOVED_UNTRACKED:
decorator = UIIcons.OVR_STAGED_REMOVE;
break;
default:
break;
}
return decorator != null ? getDecoratedImage(getEditorImage(item),
decorator) : getEditorImage(item);
}
@Override
public void dispose() {
SUBMODULE.dispose();
resourceManager.dispose();
super.dispose();
}
}
static class CommitPathLabelProvider extends ColumnLabelProvider {
public String getText(Object obj) {
return ((CommitItem) obj).path;
}
public String getToolTipText(Object element) {
return ((CommitItem) element).status.getText();
}
}
class HeaderSelectionListener extends SelectionAdapter {
private CommitItem.Order order;
private Boolean reversed;
public HeaderSelectionListener(CommitItem.Order order) {
this.order = order;
}
@Override
public void widgetSelected(SelectionEvent e) {
TreeColumn column = (TreeColumn) e.widget;
Tree tree = column.getParent();
if (column == tree.getSortColumn()) {
int currentDirection = tree.getSortDirection();
switch (currentDirection) {
case SWT.NONE:
reversed = Boolean.FALSE;
break;
case SWT.UP:
reversed = Boolean.TRUE;
break;
case SWT.DOWN:
// fall through
default:
reversed = null;
break;
}
} else
reversed = Boolean.FALSE;
if (reversed == null) {
tree.setSortColumn(null);
tree.setSortDirection(SWT.NONE);
filesViewer.setComparator(null);
return;
}
tree.setSortColumn(column);
Comparator<CommitItem> comparator;
if (reversed.booleanValue()) {
comparator = order.descending();
tree.setSortDirection(SWT.DOWN);
} else {
comparator = order;
tree.setSortDirection(SWT.UP);
}
filesViewer.setComparator(new CommitViewerComparator(comparator));
}
}
class CommitItemSelectionListener extends SelectionAdapter {
public void widgetDefaultSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) filesViewer.getSelection();
CommitItem commitItem = (CommitItem) selection.getFirstElement();
if (commitItem == null) {
return;
}
compare(commitItem);
}
}
private final class CommitItemFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement,
Object element) {
boolean result = true;
if (!showUntracked || !allowToChangeSelection) {
if (element instanceof CommitItem) {
CommitItem item = (CommitItem) element;
if (item.status == Status.UNTRACKED)
result = false;
}
}
return result;
}
}
private static final String SHOW_UNTRACKED_PREF = "CommitDialog.showUntracked"; //$NON-NLS-1$
private static final String DIALOG_SETTINGS_SECTION_NAME = Activator
.getPluginId() + ".COMMIT_DIALOG_SECTION"; //$NON-NLS-1$
/**
* A constant used for the 'commit and push button' button
*/
public static final int COMMIT_AND_PUSH_ID = 30;
FormToolkit toolkit;
CommitMessageComponent commitMessageComponent;
SpellcheckableMessageArea commitText;
Text authorText;
Text committerText;
ToolItem amendingItem;
ToolItem signedOffItem;
ToolItem changeIdItem;
ToolItem showUntrackedItem;
CachedCheckboxTreeViewer filesViewer;
Section filesSection;
Button commitButton;
Button commitAndPushButton;
ArrayList<CommitItem> items = new ArrayList<CommitItem>();
private String commitMessage = null;
private String author = null;
private String committer = null;
/**
* A collection of files that should be already checked in the table.
*/
private Set<String> preselectedFiles = Collections.emptySet();
private boolean preselectAll = false;
private ArrayList<String> selectedFiles = new ArrayList<String>();
private boolean amending = false;
private boolean amendAllowed = true;
private boolean showUntracked = true;
private boolean createChangeId = false;
private boolean allowToChangeSelection = true;
private Repository repository;
private boolean isPushRequested = false;
/**
* @param parentShell
*/
public CommitDialog(Shell parentShell) {
super(parentShell);
}
/**
* @return The message the user entered
*/
public String getCommitMessage() {
return commitMessage;
}
/**
* Preset a commit message. This might be for amending a commit.
* @param s the commit message
*/
public void setCommitMessage(String s) {
this.commitMessage = s;
}
/**
* @return the files selected by the user to commit.
*/
public Collection<String> getSelectedFiles() {
return selectedFiles;
}
/**
* Sets the files that should be checked in this table.
*
* @param preselectedFiles
* the files to be checked in the dialog's table, must not be
* <code>null</code>
*/
public void setPreselectedFiles(Set<String> preselectedFiles) {
Assert.isNotNull(preselectedFiles);
this.preselectedFiles = preselectedFiles;
}
/**
* Preselect all changed files in the commit dialog.
* Untracked files are not preselected.
* @param preselectAll
*/
public void setPreselectAll(boolean preselectAll) {
this.preselectAll = preselectAll;
}
/**
* Set the total set of changed files, including additions and
* removals
* @param repository
* @param paths paths of files potentially affected by a new commit
* @param indexDiff IndexDiff of the related repository
*/
public void setFiles(Repository repository, Set<String> paths,
IndexDiff indexDiff) {
this.repository = repository;
items.clear();
for (String path : paths) {
CommitItem item = new CommitItem();
item.status = getFileStatus(path, indexDiff);
item.submodule = FileMode.GITLINK == indexDiff.getIndexMode(path);
item.path = path;
item.problemSeverity = getProblemSeverity(repository, path);
items.add(item);
}
// initially, we sort by status plus path
Collections.sort(items, new Comparator<CommitItem>() {
public int compare(CommitItem o1, CommitItem o2) {
int diff = o1.status.ordinal() - o2.status.ordinal();
if (diff != 0)
return diff;
return o1.path.compareTo(o2.path);
}
});
}
/**
* @return The author to set for the commit
*/
public String getAuthor() {
return author;
}
/**
* Pre-set author for the commit
*
* @param author
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* @return The committer to set for the commit
*/
public String getCommitter() {
return committer;
}
/**
* Pre-set committer for the commit
*
* @param committer
*/
public void setCommitter(String committer) {
this.committer = committer;
}
/**
* @return whether the last commit is to be amended
*/
public boolean isAmending() {
return amending;
}
/**
* Pre-set whether the last commit is going to be amended
*
* @param amending
*/
public void setAmending(boolean amending) {
this.amending = amending;
}
/**
* Set whether the previous commit may be amended
*
* @param amendAllowed
*/
public void setAmendAllowed(boolean amendAllowed) {
this.amendAllowed = amendAllowed;
}
/**
* Set whether is is allowed to change the set of selected files
* @param allowToChangeSelection
*/
public void setAllowToChangeSelection(boolean allowToChangeSelection) {
this.allowToChangeSelection = allowToChangeSelection;
}
/**
* @return true if a Change-Id line for Gerrit should be created
*/
public boolean getCreateChangeId() {
return createChangeId;
}
/**
* @return true if push shall be executed
*/
public boolean isPushRequested() {
return isPushRequested;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
toolkit.adapt(parent, false, false);
commitAndPushButton = createButton(parent, COMMIT_AND_PUSH_ID,
UIText.CommitDialog_CommitAndPush, false);
commitButton = createButton(parent, IDialogConstants.OK_ID,
UIText.CommitDialog_Commit, true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
updateMessage();
}
protected void buttonPressed(int buttonId) {
if (IDialogConstants.OK_ID == buttonId)
okPressed();
else if (COMMIT_AND_PUSH_ID == buttonId) {
isPushRequested = true;
okPressed();
} else if (IDialogConstants.CANCEL_ID == buttonId)
cancelPressed();
}
@Override
protected Control createButtonBar(Composite parent) {
toolkit.adapt(parent, false, false);
return super.createButtonBar(parent);
}
@Override
protected Control createHelpControl(Composite parent) {
toolkit.adapt(parent, false, false);
Control help = super.createHelpControl(parent);
toolkit.adapt(help, false, false);
return help;
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = Activator.getDefault().getDialogSettings();
IDialogSettings section = settings
.getSection(DIALOG_SETTINGS_SECTION_NAME);
if (section == null)
section = settings.addNewSection(DIALOG_SETTINGS_SECTION_NAME);
return section;
}
/**
* Add message drop down toolbar item
*
* @param parent
* @return toolbar
*/
protected ToolBar addMessageDropDown(Composite parent) {
final ToolBar dropDownBar = new ToolBar(parent, SWT.FLAT | SWT.RIGHT);
final ToolItem dropDownItem = new ToolItem(dropDownBar, SWT.PUSH);
dropDownItem.setImage(PlatformUI.getWorkbench().getSharedImages()
.getImage("IMG_LCL_RENDERED_VIEW_MENU")); //$NON-NLS-1$
final Menu menu = new Menu(dropDownBar);
dropDownItem.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
menu.dispose();
}
});
MenuItem preferencesItem = new MenuItem(menu, SWT.PUSH);
preferencesItem.setText(UIText.CommitDialog_ConfigureLink);
preferencesItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String[] pages = new String[] { UIPreferences.PAGE_COMMIT_PREFERENCES };
PreferencesUtil.createPreferenceDialogOn(getShell(), pages[0],
pages, null).open();
}
});
dropDownItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Rectangle b = dropDownItem.getBounds();
Point p = dropDownItem.getParent().toDisplay(
new Point(b.x, b.y + b.height));
menu.setLocation(p.x, p.y);
menu.setVisible(true);
}
});
return dropDownBar;
}
@Override
protected Control createContents(Composite parent) {
toolkit = new FormToolkit(parent.getDisplay());
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
toolkit.dispose();
}
});
return super.createContents(parent);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
parent.getShell().setText(UIText.CommitDialog_CommitChanges);
container = toolkit.createComposite(container);
GridDataFactory.fillDefaults().grab(true, true).applyTo(container);
toolkit.paintBordersFor(container);
GridLayoutFactory.swtDefaults().applyTo(container);
final SashForm sashForm= new SashForm(container, SWT.VERTICAL
| SWT.FILL);
toolkit.adapt(sashForm, true, true);
sashForm.setLayoutData(GridDataFactory.fillDefaults().grab(true, true)
.create());
createMessageAndPersonArea(sashForm);
filesSection = createFileSection(sashForm);
sashForm.setWeights(new int[] { 50, 50 });
applyDialogFont(container);
container.pack();
commitText.setFocus();
Image titleImage = UIIcons.WIZBAN_CONNECT_REPO.createImage();
UIUtils.hookDisposal(parent, titleImage);
setTitleImage(titleImage);
setTitle(UIText.CommitDialog_Title);
setMessage(UIText.CommitDialog_Message, IMessageProvider.INFORMATION);
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateMessage();
}
});
updateFileSectionText();
return container;
}
private Section createFileSection(Composite container) {
Section filesSection = toolkit.createSection(container,
ExpandableComposite.TITLE_BAR
| ExpandableComposite.CLIENT_INDENT);
GridDataFactory.fillDefaults().grab(true, true).applyTo(filesSection);
Composite filesArea = toolkit.createComposite(filesSection);
filesSection.setClient(filesArea);
toolkit.paintBordersFor(filesArea);
GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2)
.applyTo(filesArea);
ToolBar filesToolbar = new ToolBar(filesSection, SWT.FLAT);
filesSection.setTextClient(filesToolbar);
PatternFilter patternFilter = new PatternFilter() {
@Override
protected boolean isLeafMatch(Viewer viewer, Object element) {
if(element instanceof CommitItem) {
CommitItem commitItem = (CommitItem) element;
return wordMatches(commitItem.path);
}
return super.isLeafMatch(viewer, element);
}
};
patternFilter.setIncludeLeadingWildcard(true);
FilteredCheckboxTree resourcesTreeComposite = new FilteredCheckboxTree(
filesArea, toolkit, SWT.FULL_SELECTION, patternFilter) {
@Override
protected WorkbenchJob doCreateRefreshJob() {
// workaround for file filter not having an explicit change
// listener
WorkbenchJob filterJob = super.doCreateRefreshJob();
filterJob.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
if (event.getResult().isOK()) {
getDisplay().asyncExec(new Runnable() {
public void run() {
updateFileSectionText();
}
});
}
}
});
return filterJob;
}
};
Tree resourcesTree = resourcesTreeComposite.getViewer().getTree();
resourcesTree.setData(FormToolkit.KEY_DRAW_BORDER,
FormToolkit.TREE_BORDER);
resourcesTreeComposite.setLayoutData(GridDataFactory.fillDefaults()
.hint(600, 200).grab(true, true).create());
resourcesTree.addSelectionListener(new CommitItemSelectionListener());
resourcesTree.setHeaderVisible(true);
TreeColumn statCol = new TreeColumn(resourcesTree, SWT.LEFT);
statCol.setText(UIText.CommitDialog_Status);
statCol.setWidth(150);
statCol.addSelectionListener(new HeaderSelectionListener(
CommitItem.Order.ByStatus));
TreeColumn resourceCol = new TreeColumn(resourcesTree, SWT.LEFT);
resourceCol.setText(UIText.CommitDialog_Path);
resourceCol.setWidth(415);
resourceCol.addSelectionListener(new HeaderSelectionListener(
CommitItem.Order.ByFile));
filesViewer = resourcesTreeComposite.getCheckboxTreeViewer();
new TreeViewerColumn(filesViewer, statCol)
.setLabelProvider(createStatusLabelProvider());
new TreeViewerColumn(filesViewer, resourceCol)
.setLabelProvider(new CommitPathLabelProvider());
ColumnViewerToolTipSupport.enableFor(filesViewer);
filesViewer.setContentProvider(new CommitFileContentProvider());
filesViewer.setUseHashlookup(true);
IDialogSettings settings = org.eclipse.egit.ui.Activator.getDefault()
.getDialogSettings();
if (settings.get(SHOW_UNTRACKED_PREF) != null) {
// note, no matter how the dialog settings are, if
// the preferences force us to include untracked files
// we must show them
showUntracked = Boolean.valueOf(settings.get(SHOW_UNTRACKED_PREF))
.booleanValue()
|| getPreferenceStore().getBoolean(
UIPreferences.COMMIT_DIALOG_INCLUDE_UNTRACKED);
}
filesViewer.addFilter(new CommitItemFilter());
filesViewer.setInput(items.toArray());
MenuManager menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(createContextMenuListener());
filesViewer.getTree().setMenu(
menuManager.createContextMenu(filesViewer.getTree()));
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateFileSectionText();
}
});
showUntrackedItem = new ToolItem(filesToolbar, SWT.CHECK);
Image showUntrackedImage = UIIcons.UNTRACKED_FILE.createImage();
UIUtils.hookDisposal(showUntrackedItem, showUntrackedImage);
showUntrackedItem.setImage(showUntrackedImage);
showUntrackedItem
.setToolTipText(UIText.CommitDialog_ShowUntrackedFiles);
showUntrackedItem.setSelection(showUntracked);
showUntrackedItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showUntracked = showUntrackedItem.getSelection();
filesViewer.refresh(true);
updateFileSectionText();
updateMessage();
}
});
ToolItem checkAllItem = new ToolItem(filesToolbar, SWT.PUSH);
Image checkImage = UIIcons.CHECK_ALL.createImage();
UIUtils.hookDisposal(checkAllItem, checkImage);
checkAllItem.setImage(checkImage);
checkAllItem.setToolTipText(UIText.CommitDialog_SelectAll);
checkAllItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filesViewer.setAllChecked(true);
updateFileSectionText();
updateMessage();
}
});
ToolItem uncheckAllItem = new ToolItem(filesToolbar, SWT.PUSH);
Image uncheckImage = UIIcons.UNCHECK_ALL.createImage();
UIUtils.hookDisposal(uncheckAllItem, uncheckImage);
uncheckAllItem.setImage(uncheckImage);
uncheckAllItem.setToolTipText(UIText.CommitDialog_DeselectAll);
uncheckAllItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filesViewer.setAllChecked(false);
updateFileSectionText();
updateMessage();
}
});
if (!allowToChangeSelection) {
amendingItem.setSelection(false);
amendingItem.setEnabled(false);
showUntrackedItem.setSelection(false);
showUntrackedItem.setEnabled(false);
checkAllItem.setEnabled(false);
uncheckAllItem.setEnabled(false);
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
if (!event.getChecked())
filesViewer.setAllChecked(true);
updateFileSectionText();
}
});
filesViewer.setAllChecked(true);
} else {
final boolean includeUntracked = getPreferenceStore().getBoolean(
UIPreferences.COMMIT_DIALOG_INCLUDE_UNTRACKED);
for (CommitItem item : items) {
if (!preselectAll && !preselectedFiles.contains(item.path))
continue;
if (item.status == Status.ASSUME_UNCHANGED)
continue;
if (!includeUntracked && item.status == Status.UNTRACKED)
continue;
filesViewer.setChecked(item, true);
}
}
statCol.pack();
resourceCol.pack();
return filesSection;
}
private Composite createMessageAndPersonArea(Composite container) {
Composite messageAndPersonArea = toolkit.createComposite(container);
GridDataFactory.fillDefaults().grab(true, true)
.applyTo(messageAndPersonArea);
GridLayoutFactory.swtDefaults().margins(0, 0).spacing(0, 0)
.applyTo(messageAndPersonArea);
Section messageSection = toolkit.createSection(messageAndPersonArea,
ExpandableComposite.TITLE_BAR
| ExpandableComposite.CLIENT_INDENT);
messageSection.setText(UIText.CommitDialog_CommitMessage);
Composite messageArea = toolkit.createComposite(messageSection);
GridLayoutFactory.fillDefaults().spacing(0, 0)
.extendedMargins(2, 2, 2, 2).applyTo(messageArea);
toolkit.paintBordersFor(messageArea);
GridDataFactory.fillDefaults().grab(true, true).applyTo(messageSection);
GridLayoutFactory.swtDefaults().applyTo(messageSection);
Composite headerArea = new Composite(messageSection, SWT.NONE);
GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(2)
.applyTo(headerArea);
ToolBar messageToolbar = new ToolBar(headerArea, SWT.FLAT
| SWT.HORIZONTAL);
GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL)
.grab(true, false).applyTo(messageToolbar);
addMessageDropDown(headerArea);
messageSection.setTextClient(headerArea);
final CommitProposalProcessor commitProposalProcessor = new CommitProposalProcessor() {
@Override
protected Collection<String> computeFileNameProposals() {
return getFileList();
}
@Override
protected Collection<String> computeMessageProposals() {
return CommitMessageHistory.getCommitHistory();
}
};
commitText = new CommitMessageArea(messageArea, commitMessage, SWT.NONE) {
@Override
protected CommitProposalProcessor getCommitProposalProcessor() {
return commitProposalProcessor;
}
};
commitText
.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
messageSection.setClient(messageArea);
Point size = commitText.getTextWidget().getSize();
int minHeight = commitText.getTextWidget().getLineHeight() * 3;
commitText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, true).hint(size).minSize(size.x, minHeight)
.align(SWT.FILL, SWT.FILL).create());
UIUtils.addBulbDecorator(commitText.getTextWidget(),
UIText.CommitDialog_ContentAssist);
Composite personArea = toolkit.createComposite(messageAndPersonArea);
toolkit.paintBordersFor(personArea);
GridLayoutFactory.swtDefaults().numColumns(2).applyTo(personArea);
GridDataFactory.fillDefaults().grab(true, false).applyTo(personArea);
toolkit.createLabel(personArea, UIText.CommitDialog_Author)
.setForeground(
toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
authorText = toolkit.createText(personArea, null);
authorText
.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
authorText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, false).create());
if (repository != null
&& repository.getRepositoryState().equals(
RepositoryState.CHERRY_PICKING_RESOLVED))
authorText.setEnabled(false);
toolkit.createLabel(personArea, UIText.CommitDialog_Committer)
.setForeground(
toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
committerText = toolkit.createText(personArea, null);
committerText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, false).create());
if (committer != null)
committerText.setText(committer);
amendingItem = new ToolItem(messageToolbar, SWT.CHECK);
amendingItem.setSelection(amending);
if (amending)
amendingItem.setEnabled(false); // if already set, don't allow any
// changes
else if (!amendAllowed)
amendingItem.setEnabled(false);
amendingItem.setToolTipText(UIText.CommitDialog_AmendPreviousCommit);
Image amendImage = UIIcons.AMEND_COMMIT.createImage();
UIUtils.hookDisposal(amendingItem, amendImage);
amendingItem.setImage(amendImage);
signedOffItem = new ToolItem(messageToolbar, SWT.CHECK);
signedOffItem.setToolTipText(UIText.CommitDialog_AddSOB);
Image signedOffImage = UIIcons.SIGNED_OFF.createImage();
UIUtils.hookDisposal(signedOffItem, signedOffImage);
signedOffItem.setImage(signedOffImage);
changeIdItem = new ToolItem(messageToolbar, SWT.CHECK);
Image changeIdImage = UIIcons.GERRIT.createImage();
UIUtils.hookDisposal(changeIdItem, changeIdImage);
changeIdItem.setImage(changeIdImage);
changeIdItem.setToolTipText(UIText.CommitDialog_AddChangeIdLabel);
final ICommitMessageComponentNotifications listener = new ICommitMessageComponentNotifications() {
public void updateSignedOffToggleSelection(boolean selection) {
signedOffItem.setSelection(selection);
}
public void updateChangeIdToggleSelection(boolean selection) {
changeIdItem.setSelection(selection);
}
public void statusUpdated() {
updateMessage();
}
};
commitMessageComponent = new CommitMessageComponent(repository,
listener);
commitMessageComponent.enableListeners(false);
commitMessageComponent.setDefaults();
commitMessageComponent.attachControls(commitText, authorText,
committerText);
commitMessageComponent.setCommitMessage(commitMessage);
commitMessageComponent.setAuthor(author);
commitMessageComponent.setCommitter(committer);
commitMessageComponent.setAmending(amending);
commitMessageComponent.setFilesToCommit(getFileList());
amendingItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent.setAmendingButtonSelection(amendingItem
.getSelection());
}
});
changeIdItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent.setChangeIdButtonSelection(changeIdItem
.getSelection());
}
});
signedOffItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent
.setSignedOffButtonSelection(signedOffItem
.getSelection());
}
});
commitMessageComponent.updateUI();
commitMessageComponent.enableListeners(true);
return messageAndPersonArea;
}
private static CellLabelProvider createStatusLabelProvider() {
CommitStatusLabelProvider baseProvider = new CommitStatusLabelProvider();
ProblemLabelDecorator decorator = new ProblemLabelDecorator(null);
return new DecoratingStyledCellLabelProvider(baseProvider, decorator, null) {
@Override
public String getToolTipText(Object element) {
return ((CommitItem) element).status.getText();
}
};
}
private void updateMessage() {
if (commitButton == null)
// Not yet fully initialized.
return;
String message = null;
int type = IMessageProvider.NONE;
String commitMsg = commitMessageComponent.getCommitMessage();
if (commitMsg == null || commitMsg.trim().length() == 0) {
message = UIText.CommitDialog_Message;
type = IMessageProvider.INFORMATION;
} else if (!isCommitWithoutFilesAllowed()) {
message = UIText.CommitDialog_MessageNoFilesSelected;
type = IMessageProvider.INFORMATION;
} else {
CommitStatus status = commitMessageComponent.getStatus();
message = status.getMessage();
type = status.getMessageType();
}
setMessage(message, type);
boolean commitEnabled = type == IMessageProvider.WARNING
|| type == IMessageProvider.NONE;
commitButton.setEnabled(commitEnabled);
commitAndPushButton.setEnabled(commitEnabled);
}
private boolean isCommitWithoutFilesAllowed() {
if (filesViewer.getCheckedElements().length > 0)
return true;
if (amendingItem.getSelection())
return true;
return CommitHelper.isCommitWithoutFilesAllowed(repository);
}
private Collection<String> getFileList() {
Collection<String> result = new ArrayList<String>();
for (CommitItem item : items) {
result.add(item.path);
}
return result;
}
private void updateFileSectionText() {
filesSection.setText(MessageFormat.format(UIText.CommitDialog_Files,
Integer.valueOf(filesViewer.getCheckedElements().length),
Integer.valueOf(filesViewer.getTree().getItemCount())));
}
private IMenuListener createContextMenuListener() {
return new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
if (!allowToChangeSelection)
return;
final IStructuredSelection selection = (IStructuredSelection) filesViewer
.getSelection();
if (selection.isEmpty())
return;
if (selection.size() == 1
&& selection.getFirstElement() instanceof CommitItem) {
CommitItem commitItem = (CommitItem) selection
.getFirstElement();
manager.add(createCompareAction(commitItem));
}
manager.add(createAddAction(selection));
}
};
}
private Action createCompareAction(final CommitItem commitItem) {
return new Action(UIText.CommitDialog_CompareWithHeadRevision) {
@Override
public void run() {
compare(commitItem);
}
};
}
private Action createAddAction(final IStructuredSelection selection) {
return new Action(UIText.CommitDialog_AddFileOnDiskToIndex) {
public void run() {
AddCommand addCommand = new Git(repository).add();
for (Iterator<?> it = selection.iterator(); it.hasNext();) {
CommitItem commitItem = (CommitItem) it.next();
addCommand.addFilepattern(commitItem.path);
}
try {
addCommand.call();
} catch (Exception e) {
Activator.logError(UIText.CommitDialog_ErrorAddingFiles, e);
}
for (Iterator<?> it = selection.iterator(); it.hasNext();) {
CommitItem commitItem = (CommitItem) it.next();
try {
commitItem.status = getFileStatus(commitItem.path);
} catch (IOException e) {
Activator.logError(
UIText.CommitDialog_ErrorAddingFiles, e);
}
}
filesViewer.refresh(true);
}
};
}
/** Retrieve file status
* @param path
* @return file status
* @throws IOException
*/
private Status getFileStatus(String path) throws IOException {
AdaptableFileTreeIterator fileTreeIterator = new AdaptableFileTreeIterator(
repository, ResourcesPlugin.getWorkspace().getRoot());
IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, fileTreeIterator);
Set<String> repositoryPaths = Collections.singleton(path);
indexDiff.setFilter(PathFilterGroup.createFromStrings(repositoryPaths));
indexDiff.diff(null, 0, 0, ""); //$NON-NLS-1$
return getFileStatus(path, indexDiff);
}
/** Retrieve file status from an already calculated IndexDiff
* @param path
* @param indexDiff
* @return file status
*/
private static Status getFileStatus(String path, IndexDiff indexDiff) {
if (indexDiff.getAssumeUnchanged().contains(path)) {
return Status.ASSUME_UNCHANGED;
} else if (indexDiff.getAdded().contains(path)) {
// added
if (indexDiff.getModified().contains(path))
return Status.ADDED_INDEX_DIFF;
else
return Status.ADDED;
} else if (indexDiff.getChanged().contains(path)) {
// changed
if (indexDiff.getModified().contains(path))
return Status.MODIFIED_INDEX_DIFF;
else
return Status.MODIFIED;
} else if (indexDiff.getUntracked().contains(path)) {
// untracked
if (indexDiff.getRemoved().contains(path))
return Status.REMOVED_UNTRACKED;
else
return Status.UNTRACKED;
} else if (indexDiff.getRemoved().contains(path)) {
// removed
return Status.REMOVED;
} else if (indexDiff.getMissing().contains(path)) {
// missing
return Status.REMOVED_NOT_STAGED;
} else if (indexDiff.getModified().contains(path)) {
// modified (and not changed!)
return Status.MODIFIED_NOT_STAGED;
}
return Status.UNKNOWN;
}
private static int getProblemSeverity(Repository repository, String path) {
IFile file = ResourceUtil.getFileForLocation(repository, path);
if (file != null) {
try {
int severity = file.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE);
return severity;
} catch (CoreException e) {
// Fall back to below
}
}
return IProblemDecoratable.SEVERITY_NONE;
}
@Override
protected void okPressed() {
if (!isCommitWithoutFilesAllowed()) {
MessageDialog.openWarning(getShell(), UIText.CommitDialog_ErrorNoItemsSelected, UIText.CommitDialog_ErrorNoItemsSelectedToBeCommitted);
return;
}
if (!commitMessageComponent.checkCommitInfo())
return;
Object[] checkedElements = filesViewer.getCheckedElements();
selectedFiles.clear();
for (Object obj : checkedElements)
selectedFiles.add(((CommitItem) obj).path);
amending = commitMessageComponent.isAmending();
commitMessage = commitMessageComponent.getCommitMessage();
author = commitMessageComponent.getAuthor();
committer = commitMessageComponent.getCommitter();
createChangeId = changeIdItem.getSelection();
IDialogSettings settings = org.eclipse.egit.ui.Activator
.getDefault().getDialogSettings();
settings.put(SHOW_UNTRACKED_PREF, showUntracked);
CommitMessageHistory.saveCommitHistory(getCommitMessage());
super.okPressed();
}
@Override
protected int getShellStyle() {
return super.getShellStyle() | SWT.RESIZE;
}
private void compare(CommitItem commitItem) {
IFile file = findFile(commitItem.path);
if (file == null
|| RepositoryProvider.getProvider(file.getProject()) == null)
CompareUtils
.compareHeadWithWorkingTree(repository, commitItem.path);
else
CompareUtils.compareHeadWithWorkspace(repository, file);
}
private IFile findFile(String path) {
return ResourceUtil.getFileForLocation(repository, path);
}
}
class CommitItem implements IProblemDecoratable {
Status status;
String path;
boolean submodule;
int problemSeverity;
public int getProblemSeverity() {
return problemSeverity;
}
/** The ordinal of this {@link Enum} is used to provide the "native" sorting of the list */
public static enum Status {
/** */
ADDED(UIText.CommitDialog_StatusAdded),
/** */
MODIFIED(UIText.CommitDialog_StatusModified),
/** */
REMOVED(UIText.CommitDialog_StatusRemoved),
/** */
ADDED_INDEX_DIFF(UIText.CommitDialog_StatusAddedIndexDiff),
/** */
MODIFIED_INDEX_DIFF(UIText.CommitDialog_StatusModifiedIndexDiff),
/** */
MODIFIED_NOT_STAGED(UIText.CommitDialog_StatusModifiedNotStaged),
/** */
REMOVED_NOT_STAGED(UIText.CommitDialog_StatusRemovedNotStaged),
/** */
UNTRACKED(UIText.CommitDialog_StatusUntracked),
/** */
REMOVED_UNTRACKED(UIText.CommitDialog_StatusRemovedUntracked),
/** */
ASSUME_UNCHANGED(UIText.CommitDialog_StatusAssumeUnchaged),
/** */
UNKNOWN(UIText.CommitDialog_StatusUnknown);
public String getText() {
return myText;
}
private final String myText;
private Status(String text) {
myText = text;
}
}
public static enum Order implements Comparator<CommitItem> {
ByStatus() {
public int compare(CommitItem o1, CommitItem o2) {
return o1.status.compareTo(o2.status);
}
},
ByFile() {
public int compare(CommitItem o1, CommitItem o2) {
return o1.path.compareTo(
o2.path);
}
};
public Comparator<CommitItem> ascending() {
return this;
}
public Comparator<CommitItem> descending() {
return Collections.reverseOrder(this);
}
}
}
class CommitViewerComparator extends ViewerComparator {
public CommitViewerComparator(Comparator comparator){
super(comparator);
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
return getComparator().compare(e1, e2);
}
}
| org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/dialogs/CommitDialog.java | /*******************************************************************************
* Copyright (C) 2007, Dave Watson <[email protected]>
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2008, Robin Rosenberg <[email protected]>
* Copyright (C) 2007, Shawn O. Pearce <[email protected]>
* Copyright (C) 2011, Mathias Kinzler <[email protected]>
* Copyright (C) 2012, Daniel Megert <[email protected]>
* Copyright (C) 2012, 2013 Robin Stocker <[email protected]>
* Copyright (C) 2012, IBM Corporation (Markus Keller <[email protected]>)
* Copyright (C) 2013, François Rey <eclipse.org_@_francois_._rey_._name>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.dialogs;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.egit.core.AdaptableFileTreeIterator;
import org.eclipse.egit.core.internal.util.ResourceUtil;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.egit.ui.UIUtils;
import org.eclipse.egit.ui.internal.CachedCheckboxTreeViewer;
import org.eclipse.egit.ui.internal.CompareUtils;
import org.eclipse.egit.ui.internal.FilteredCheckboxTree;
import org.eclipse.egit.ui.internal.UIIcons;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.commit.CommitHelper;
import org.eclipse.egit.ui.internal.commit.CommitMessageHistory;
import org.eclipse.egit.ui.internal.commit.CommitProposalProcessor;
import org.eclipse.egit.ui.internal.decorators.IProblemDecoratable;
import org.eclipse.egit.ui.internal.decorators.ProblemLabelDecorator;
import org.eclipse.egit.ui.internal.dialogs.CommitItem.Status;
import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponent.CommitStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider;
import org.eclipse.jface.viewers.DecorationOverlayIcon;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.IndexDiff;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.progress.WorkbenchJob;
/**
* Dialog is shown to user when they request to commit files. Changes in the
* selected portion of the tree are shown.
*/
public class CommitDialog extends TitleAreaDialog {
private static IPreferenceStore getPreferenceStore() {
return org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore();
}
static class CommitFileContentProvider extends BaseWorkbenchContentProvider {
@Override
public Object[] getElements(Object element) {
if (element instanceof Object[])
return (Object[]) element;
if (element instanceof Collection)
return ((Collection) element).toArray();
return new Object[0];
}
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
return false;
}
}
static class CommitStatusLabelProvider extends BaseLabelProvider implements
IStyledLabelProvider {
private Image DEFAULT = PlatformUI.getWorkbench().getSharedImages()
.getImage(ISharedImages.IMG_OBJ_FILE);
private ResourceManager resourceManager = new LocalResourceManager(
JFaceResources.getResources());
private final Image SUBMODULE = UIIcons.REPOSITORY.createImage();
private Image getEditorImage(CommitItem item) {
if (!item.submodule) {
Image image = DEFAULT;
String name = new Path(item.path).lastSegment();
if (name != null) {
ImageDescriptor descriptor = PlatformUI.getWorkbench()
.getEditorRegistry().getImageDescriptor(name);
image = (Image) this.resourceManager.get(descriptor);
}
return image;
} else
return SUBMODULE;
}
private Image getDecoratedImage(Image base, ImageDescriptor decorator) {
DecorationOverlayIcon decorated = new DecorationOverlayIcon(base,
decorator, IDecoration.BOTTOM_RIGHT);
return (Image) this.resourceManager.get(decorated);
}
public StyledString getStyledText(Object element) {
return new StyledString();
}
public Image getImage(Object element) {
CommitItem item = (CommitItem) element;
ImageDescriptor decorator = null;
switch (item.status) {
case UNTRACKED:
decorator = UIIcons.OVR_UNTRACKED;
break;
case ADDED:
case ADDED_INDEX_DIFF:
decorator = UIIcons.OVR_STAGED_ADD;
break;
case REMOVED:
case REMOVED_NOT_STAGED:
case REMOVED_UNTRACKED:
decorator = UIIcons.OVR_STAGED_REMOVE;
break;
default:
break;
}
return decorator != null ? getDecoratedImage(getEditorImage(item),
decorator) : getEditorImage(item);
}
@Override
public void dispose() {
SUBMODULE.dispose();
resourceManager.dispose();
super.dispose();
}
}
static class CommitPathLabelProvider extends ColumnLabelProvider {
public String getText(Object obj) {
return ((CommitItem) obj).path;
}
public String getToolTipText(Object element) {
return ((CommitItem) element).status.getText();
}
}
class HeaderSelectionListener extends SelectionAdapter {
private CommitItem.Order order;
private Boolean reversed;
public HeaderSelectionListener(CommitItem.Order order) {
this.order = order;
}
@Override
public void widgetSelected(SelectionEvent e) {
TreeColumn column = (TreeColumn) e.widget;
Tree tree = column.getParent();
if (column == tree.getSortColumn()) {
int currentDirection = tree.getSortDirection();
switch (currentDirection) {
case SWT.NONE:
reversed = Boolean.FALSE;
break;
case SWT.UP:
reversed = Boolean.TRUE;
break;
case SWT.DOWN:
// fall through
default:
reversed = null;
break;
}
} else
reversed = Boolean.FALSE;
if (reversed == null) {
tree.setSortColumn(null);
tree.setSortDirection(SWT.NONE);
filesViewer.setComparator(null);
return;
}
tree.setSortColumn(column);
Comparator<CommitItem> comparator;
if (reversed.booleanValue()) {
comparator = order.descending();
tree.setSortDirection(SWT.DOWN);
} else {
comparator = order;
tree.setSortDirection(SWT.UP);
}
filesViewer.setComparator(new CommitViewerComparator(comparator));
}
}
class CommitItemSelectionListener extends SelectionAdapter {
public void widgetDefaultSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) filesViewer.getSelection();
CommitItem commitItem = (CommitItem) selection.getFirstElement();
if (commitItem == null) {
return;
}
compare(commitItem);
}
}
private final class CommitItemFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement,
Object element) {
boolean result = true;
if (!showUntracked || !allowToChangeSelection) {
if (element instanceof CommitItem) {
CommitItem item = (CommitItem) element;
if (item.status == Status.UNTRACKED)
result = false;
}
}
return result;
}
}
private static final String SHOW_UNTRACKED_PREF = "CommitDialog.showUntracked"; //$NON-NLS-1$
private static final String DIALOG_SETTINGS_SECTION_NAME = Activator
.getPluginId() + ".COMMIT_DIALOG_SECTION"; //$NON-NLS-1$
/**
* A constant used for the 'commit and push button' button
*/
public static final int COMMIT_AND_PUSH_ID = 30;
FormToolkit toolkit;
CommitMessageComponent commitMessageComponent;
SpellcheckableMessageArea commitText;
Text authorText;
Text committerText;
ToolItem amendingItem;
ToolItem signedOffItem;
ToolItem changeIdItem;
ToolItem showUntrackedItem;
CachedCheckboxTreeViewer filesViewer;
Section filesSection;
Button commitButton;
Button commitAndPushButton;
ArrayList<CommitItem> items = new ArrayList<CommitItem>();
private String commitMessage = null;
private String author = null;
private String committer = null;
/**
* A collection of files that should be already checked in the table.
*/
private Set<String> preselectedFiles = Collections.emptySet();
private boolean preselectAll = false;
private ArrayList<String> selectedFiles = new ArrayList<String>();
private boolean amending = false;
private boolean amendAllowed = true;
private boolean showUntracked = true;
private boolean createChangeId = false;
private boolean allowToChangeSelection = true;
private Repository repository;
private boolean isPushRequested = false;
/**
* @param parentShell
*/
public CommitDialog(Shell parentShell) {
super(parentShell);
}
/**
* @return The message the user entered
*/
public String getCommitMessage() {
return commitMessage;
}
/**
* Preset a commit message. This might be for amending a commit.
* @param s the commit message
*/
public void setCommitMessage(String s) {
this.commitMessage = s;
}
/**
* @return the files selected by the user to commit.
*/
public Collection<String> getSelectedFiles() {
return selectedFiles;
}
/**
* Sets the files that should be checked in this table.
*
* @param preselectedFiles
* the files to be checked in the dialog's table, must not be
* <code>null</code>
*/
public void setPreselectedFiles(Set<String> preselectedFiles) {
Assert.isNotNull(preselectedFiles);
this.preselectedFiles = preselectedFiles;
}
/**
* Preselect all changed files in the commit dialog.
* Untracked files are not preselected.
* @param preselectAll
*/
public void setPreselectAll(boolean preselectAll) {
this.preselectAll = preselectAll;
}
/**
* Set the total set of changed files, including additions and
* removals
* @param repository
* @param paths paths of files potentially affected by a new commit
* @param indexDiff IndexDiff of the related repository
*/
public void setFiles(Repository repository, Set<String> paths,
IndexDiff indexDiff) {
this.repository = repository;
items.clear();
for (String path : paths) {
CommitItem item = new CommitItem();
item.status = getFileStatus(path, indexDiff);
item.submodule = FileMode.GITLINK == indexDiff.getIndexMode(path);
item.path = path;
item.problemSeverity = getProblemSeverity(repository, path);
items.add(item);
}
// initially, we sort by status plus path
Collections.sort(items, new Comparator<CommitItem>() {
public int compare(CommitItem o1, CommitItem o2) {
int diff = o1.status.ordinal() - o2.status.ordinal();
if (diff != 0)
return diff;
return o1.path.compareTo(o2.path);
}
});
}
/**
* @return The author to set for the commit
*/
public String getAuthor() {
return author;
}
/**
* Pre-set author for the commit
*
* @param author
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* @return The committer to set for the commit
*/
public String getCommitter() {
return committer;
}
/**
* Pre-set committer for the commit
*
* @param committer
*/
public void setCommitter(String committer) {
this.committer = committer;
}
/**
* @return whether the last commit is to be amended
*/
public boolean isAmending() {
return amending;
}
/**
* Pre-set whether the last commit is going to be amended
*
* @param amending
*/
public void setAmending(boolean amending) {
this.amending = amending;
}
/**
* Set whether the previous commit may be amended
*
* @param amendAllowed
*/
public void setAmendAllowed(boolean amendAllowed) {
this.amendAllowed = amendAllowed;
}
/**
* Set whether is is allowed to change the set of selected files
* @param allowToChangeSelection
*/
public void setAllowToChangeSelection(boolean allowToChangeSelection) {
this.allowToChangeSelection = allowToChangeSelection;
}
/**
* @return true if a Change-Id line for Gerrit should be created
*/
public boolean getCreateChangeId() {
return createChangeId;
}
/**
* @return true if push shall be executed
*/
public boolean isPushRequested() {
return isPushRequested;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
toolkit.adapt(parent, false, false);
commitAndPushButton = createButton(parent, COMMIT_AND_PUSH_ID,
UIText.CommitDialog_CommitAndPush, false);
commitButton = createButton(parent, IDialogConstants.OK_ID,
UIText.CommitDialog_Commit, true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
updateMessage();
}
protected void buttonPressed(int buttonId) {
if (IDialogConstants.OK_ID == buttonId)
okPressed();
else if (COMMIT_AND_PUSH_ID == buttonId) {
isPushRequested = true;
okPressed();
} else if (IDialogConstants.CANCEL_ID == buttonId)
cancelPressed();
}
@Override
protected Control createButtonBar(Composite parent) {
toolkit.adapt(parent, false, false);
return super.createButtonBar(parent);
}
@Override
protected Control createHelpControl(Composite parent) {
toolkit.adapt(parent, false, false);
Control help = super.createHelpControl(parent);
toolkit.adapt(help, false, false);
return help;
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = Activator.getDefault().getDialogSettings();
IDialogSettings section = settings
.getSection(DIALOG_SETTINGS_SECTION_NAME);
if (section == null)
section = settings.addNewSection(DIALOG_SETTINGS_SECTION_NAME);
return section;
}
/**
* Add message drop down toolbar item
*
* @param parent
* @return toolbar
*/
protected ToolBar addMessageDropDown(Composite parent) {
final ToolBar dropDownBar = new ToolBar(parent, SWT.FLAT | SWT.RIGHT);
final ToolItem dropDownItem = new ToolItem(dropDownBar, SWT.PUSH);
dropDownItem.setImage(PlatformUI.getWorkbench().getSharedImages()
.getImage("IMG_LCL_RENDERED_VIEW_MENU")); //$NON-NLS-1$
final Menu menu = new Menu(dropDownBar);
dropDownItem.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
menu.dispose();
}
});
MenuItem preferencesItem = new MenuItem(menu, SWT.PUSH);
preferencesItem.setText(UIText.CommitDialog_ConfigureLink);
preferencesItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String[] pages = new String[] { UIPreferences.PAGE_COMMIT_PREFERENCES };
PreferencesUtil.createPreferenceDialogOn(getShell(), pages[0],
pages, null).open();
}
});
dropDownItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Rectangle b = dropDownItem.getBounds();
Point p = dropDownItem.getParent().toDisplay(
new Point(b.x, b.y + b.height));
menu.setLocation(p.x, p.y);
menu.setVisible(true);
}
});
return dropDownBar;
}
@Override
protected Control createContents(Composite parent) {
toolkit = new FormToolkit(parent.getDisplay());
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
toolkit.dispose();
}
});
return super.createContents(parent);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
parent.getShell().setText(UIText.CommitDialog_CommitChanges);
container = toolkit.createComposite(container);
GridDataFactory.fillDefaults().grab(true, true).applyTo(container);
toolkit.paintBordersFor(container);
GridLayoutFactory.swtDefaults().applyTo(container);
final SashForm sashForm= new SashForm(container, SWT.VERTICAL
| SWT.FILL);
toolkit.adapt(sashForm, true, true);
sashForm.setLayoutData(GridDataFactory.fillDefaults().grab(true, true)
.create());
createMessageAndPersonArea(sashForm);
filesSection = createFileSection(sashForm);
sashForm.setWeights(new int[] { 50, 50 });
applyDialogFont(container);
container.pack();
commitText.setFocus();
Image titleImage = UIIcons.WIZBAN_CONNECT_REPO.createImage();
UIUtils.hookDisposal(parent, titleImage);
setTitleImage(titleImage);
setTitle(UIText.CommitDialog_Title);
setMessage(UIText.CommitDialog_Message, IMessageProvider.INFORMATION);
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateMessage();
}
});
updateFileSectionText();
return container;
}
private Section createFileSection(Composite container) {
Section filesSection = toolkit.createSection(container,
ExpandableComposite.TITLE_BAR
| ExpandableComposite.CLIENT_INDENT);
GridDataFactory.fillDefaults().grab(true, true).applyTo(filesSection);
Composite filesArea = toolkit.createComposite(filesSection);
filesSection.setClient(filesArea);
toolkit.paintBordersFor(filesArea);
GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2)
.applyTo(filesArea);
ToolBar filesToolbar = new ToolBar(filesSection, SWT.FLAT);
filesSection.setTextClient(filesToolbar);
PatternFilter patternFilter = new PatternFilter() {
@Override
protected boolean isLeafMatch(Viewer viewer, Object element) {
if(element instanceof CommitItem) {
CommitItem commitItem = (CommitItem) element;
return wordMatches(commitItem.path);
}
return super.isLeafMatch(viewer, element);
}
};
patternFilter.setIncludeLeadingWildcard(true);
FilteredCheckboxTree resourcesTreeComposite = new FilteredCheckboxTree(
filesArea, toolkit, SWT.FULL_SELECTION, patternFilter) {
@Override
protected WorkbenchJob doCreateRefreshJob() {
// workaround for file filter not having an explicit change
// listener
WorkbenchJob filterJob = super.doCreateRefreshJob();
filterJob.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
if (event.getResult().isOK()) {
getDisplay().asyncExec(new Runnable() {
public void run() {
updateFileSectionText();
}
});
}
}
});
return filterJob;
}
};
Tree resourcesTree = resourcesTreeComposite.getViewer().getTree();
resourcesTree.setData(FormToolkit.KEY_DRAW_BORDER,
FormToolkit.TREE_BORDER);
resourcesTreeComposite.setLayoutData(GridDataFactory.fillDefaults()
.hint(600, 200).grab(true, true).create());
resourcesTree.addSelectionListener(new CommitItemSelectionListener());
resourcesTree.setHeaderVisible(true);
TreeColumn statCol = new TreeColumn(resourcesTree, SWT.LEFT);
statCol.setText(UIText.CommitDialog_Status);
statCol.setWidth(150);
statCol.addSelectionListener(new HeaderSelectionListener(
CommitItem.Order.ByStatus));
TreeColumn resourceCol = new TreeColumn(resourcesTree, SWT.LEFT);
resourceCol.setText(UIText.CommitDialog_Path);
resourceCol.setWidth(415);
resourceCol.addSelectionListener(new HeaderSelectionListener(
CommitItem.Order.ByFile));
filesViewer = resourcesTreeComposite.getCheckboxTreeViewer();
new TreeViewerColumn(filesViewer, statCol)
.setLabelProvider(createStatusLabelProvider());
new TreeViewerColumn(filesViewer, resourceCol)
.setLabelProvider(new CommitPathLabelProvider());
ColumnViewerToolTipSupport.enableFor(filesViewer);
filesViewer.setContentProvider(new CommitFileContentProvider());
filesViewer.setUseHashlookup(true);
IDialogSettings settings = org.eclipse.egit.ui.Activator.getDefault()
.getDialogSettings();
if (settings.get(SHOW_UNTRACKED_PREF) != null) {
// note, no matter how the dialog settings are, if
// the preferences force us to include untracked files
// we must show them
showUntracked = Boolean.valueOf(settings.get(SHOW_UNTRACKED_PREF))
.booleanValue()
|| getPreferenceStore().getBoolean(
UIPreferences.COMMIT_DIALOG_INCLUDE_UNTRACKED);
}
filesViewer.addFilter(new CommitItemFilter());
filesViewer.setInput(items.toArray());
MenuManager menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(createContextMenuListener());
filesViewer.getTree().setMenu(
menuManager.createContextMenu(filesViewer.getTree()));
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateFileSectionText();
}
});
showUntrackedItem = new ToolItem(filesToolbar, SWT.CHECK);
Image showUntrackedImage = UIIcons.UNTRACKED_FILE.createImage();
UIUtils.hookDisposal(showUntrackedItem, showUntrackedImage);
showUntrackedItem.setImage(showUntrackedImage);
showUntrackedItem
.setToolTipText(UIText.CommitDialog_ShowUntrackedFiles);
showUntrackedItem.setSelection(showUntracked);
showUntrackedItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showUntracked = showUntrackedItem.getSelection();
filesViewer.refresh(true);
updateFileSectionText();
updateMessage();
}
});
ToolItem checkAllItem = new ToolItem(filesToolbar, SWT.PUSH);
Image checkImage = UIIcons.CHECK_ALL.createImage();
UIUtils.hookDisposal(checkAllItem, checkImage);
checkAllItem.setImage(checkImage);
checkAllItem.setToolTipText(UIText.CommitDialog_SelectAll);
checkAllItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filesViewer.setAllChecked(true);
updateFileSectionText();
updateMessage();
}
});
ToolItem uncheckAllItem = new ToolItem(filesToolbar, SWT.PUSH);
Image uncheckImage = UIIcons.UNCHECK_ALL.createImage();
UIUtils.hookDisposal(uncheckAllItem, uncheckImage);
uncheckAllItem.setImage(uncheckImage);
uncheckAllItem.setToolTipText(UIText.CommitDialog_DeselectAll);
uncheckAllItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filesViewer.setAllChecked(false);
updateFileSectionText();
updateMessage();
}
});
if (!allowToChangeSelection) {
amendingItem.setSelection(false);
amendingItem.setEnabled(false);
showUntrackedItem.setSelection(false);
showUntrackedItem.setEnabled(false);
checkAllItem.setEnabled(false);
uncheckAllItem.setEnabled(false);
filesViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
if (!event.getChecked())
filesViewer.setAllChecked(true);
updateFileSectionText();
}
});
filesViewer.setAllChecked(true);
} else {
final boolean includeUntracked = getPreferenceStore().getBoolean(
UIPreferences.COMMIT_DIALOG_INCLUDE_UNTRACKED);
for (CommitItem item : items) {
if (!preselectAll && !preselectedFiles.contains(item.path))
continue;
if (item.status == Status.ASSUME_UNCHANGED)
continue;
if (!includeUntracked && item.status == Status.UNTRACKED)
continue;
filesViewer.setChecked(item, true);
}
}
statCol.pack();
resourceCol.pack();
return filesSection;
}
private Composite createMessageAndPersonArea(Composite container) {
Composite messageAndPersonArea = toolkit.createComposite(container);
GridDataFactory.fillDefaults().grab(true, true)
.applyTo(messageAndPersonArea);
GridLayoutFactory.swtDefaults().margins(0, 0).spacing(0, 0)
.applyTo(messageAndPersonArea);
Section messageSection = toolkit.createSection(messageAndPersonArea,
ExpandableComposite.TITLE_BAR
| ExpandableComposite.CLIENT_INDENT);
messageSection.setText(UIText.CommitDialog_CommitMessage);
Composite messageArea = toolkit.createComposite(messageSection);
GridLayoutFactory.fillDefaults().spacing(0, 0)
.extendedMargins(2, 2, 2, 2).applyTo(messageArea);
toolkit.paintBordersFor(messageArea);
GridDataFactory.fillDefaults().grab(true, true).applyTo(messageSection);
GridLayoutFactory.swtDefaults().applyTo(messageSection);
Composite headerArea = new Composite(messageSection, SWT.NONE);
GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(2)
.applyTo(headerArea);
ToolBar messageToolbar = new ToolBar(headerArea, SWT.FLAT
| SWT.HORIZONTAL);
GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL)
.grab(true, false).applyTo(messageToolbar);
addMessageDropDown(headerArea);
messageSection.setTextClient(headerArea);
final CommitProposalProcessor commitProposalProcessor = new CommitProposalProcessor() {
@Override
protected Collection<String> computeFileNameProposals() {
return getFileList();
}
@Override
protected Collection<String> computeMessageProposals() {
return CommitMessageHistory.getCommitHistory();
}
};
commitText = new CommitMessageArea(messageArea, commitMessage, SWT.NONE) {
@Override
protected CommitProposalProcessor getCommitProposalProcessor() {
return commitProposalProcessor;
}
};
commitText
.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
messageSection.setClient(messageArea);
Point size = commitText.getTextWidget().getSize();
int minHeight = commitText.getTextWidget().getLineHeight() * 3;
commitText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, true).hint(size).minSize(size.x, minHeight)
.align(SWT.FILL, SWT.FILL).create());
UIUtils.addBulbDecorator(commitText.getTextWidget(),
UIText.CommitDialog_ContentAssist);
Composite personArea = toolkit.createComposite(messageAndPersonArea);
toolkit.paintBordersFor(personArea);
GridLayoutFactory.swtDefaults().numColumns(2).applyTo(personArea);
GridDataFactory.fillDefaults().grab(true, false).applyTo(personArea);
toolkit.createLabel(personArea, UIText.CommitDialog_Author)
.setForeground(
toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
authorText = toolkit.createText(personArea, null);
authorText
.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
authorText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, false).create());
if (repository != null
&& repository.getRepositoryState().equals(
RepositoryState.CHERRY_PICKING_RESOLVED))
authorText.setEnabled(false);
toolkit.createLabel(personArea, UIText.CommitDialog_Committer)
.setForeground(
toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
committerText = toolkit.createText(personArea, null);
committerText.setLayoutData(GridDataFactory.fillDefaults()
.grab(true, false).create());
if (committer != null)
committerText.setText(committer);
amendingItem = new ToolItem(messageToolbar, SWT.CHECK);
amendingItem.setSelection(amending);
if (amending)
amendingItem.setEnabled(false); // if already set, don't allow any
// changes
else if (!amendAllowed)
amendingItem.setEnabled(false);
amendingItem.setToolTipText(UIText.CommitDialog_AmendPreviousCommit);
Image amendImage = UIIcons.AMEND_COMMIT.createImage();
UIUtils.hookDisposal(amendingItem, amendImage);
amendingItem.setImage(amendImage);
signedOffItem = new ToolItem(messageToolbar, SWT.CHECK);
signedOffItem.setToolTipText(UIText.CommitDialog_AddSOB);
Image signedOffImage = UIIcons.SIGNED_OFF.createImage();
UIUtils.hookDisposal(signedOffItem, signedOffImage);
signedOffItem.setImage(signedOffImage);
changeIdItem = new ToolItem(messageToolbar, SWT.CHECK);
Image changeIdImage = UIIcons.GERRIT.createImage();
UIUtils.hookDisposal(changeIdItem, changeIdImage);
changeIdItem.setImage(changeIdImage);
changeIdItem.setToolTipText(UIText.CommitDialog_AddChangeIdLabel);
final ICommitMessageComponentNotifications listener = new ICommitMessageComponentNotifications() {
public void updateSignedOffToggleSelection(boolean selection) {
signedOffItem.setSelection(selection);
}
public void updateChangeIdToggleSelection(boolean selection) {
changeIdItem.setSelection(selection);
}
public void statusUpdated() {
updateMessage();
}
};
commitMessageComponent = new CommitMessageComponent(repository,
listener);
commitMessageComponent.enableListeners(false);
commitMessageComponent.setDefaults();
commitMessageComponent.attachControls(commitText, authorText,
committerText);
commitMessageComponent.setCommitMessage(commitMessage);
commitMessageComponent.setAuthor(author);
commitMessageComponent.setCommitter(committer);
commitMessageComponent.setAmending(amending);
commitMessageComponent.setFilesToCommit(getFileList());
amendingItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent.setAmendingButtonSelection(amendingItem
.getSelection());
}
});
changeIdItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent.setChangeIdButtonSelection(changeIdItem
.getSelection());
}
});
signedOffItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
commitMessageComponent
.setSignedOffButtonSelection(signedOffItem
.getSelection());
}
});
commitMessageComponent.updateUI();
commitMessageComponent.enableListeners(true);
return messageAndPersonArea;
}
private static CellLabelProvider createStatusLabelProvider() {
CommitStatusLabelProvider baseProvider = new CommitStatusLabelProvider();
ProblemLabelDecorator decorator = new ProblemLabelDecorator(null);
return new DecoratingStyledCellLabelProvider(baseProvider, decorator, null) {
@Override
public String getToolTipText(Object element) {
return ((CommitItem) element).status.getText();
}
};
}
private void updateMessage() {
if (commitButton == null)
// Not yet fully initialized.
return;
String message = null;
int type = IMessageProvider.NONE;
String commitMsg = commitMessageComponent.getCommitMessage();
if (commitMsg == null || commitMsg.trim().length() == 0) {
message = UIText.CommitDialog_Message;
type = IMessageProvider.INFORMATION;
} else if (!isCommitWithoutFilesAllowed()) {
message = UIText.CommitDialog_MessageNoFilesSelected;
type = IMessageProvider.INFORMATION;
} else {
CommitStatus status = commitMessageComponent.getStatus();
message = status.getMessage();
type = status.getMessageType();
}
setMessage(message, type);
boolean commitEnabled = type == IMessageProvider.WARNING
|| type == IMessageProvider.NONE;
commitButton.setEnabled(commitEnabled);
commitAndPushButton.setEnabled(commitEnabled);
}
private boolean isCommitWithoutFilesAllowed() {
if (filesViewer.getCheckedElements().length > 0)
return true;
if (amendingItem.getSelection())
return true;
return CommitHelper.isCommitWithoutFilesAllowed(repository);
}
private Collection<String> getFileList() {
Collection<String> result = new ArrayList<String>();
for (CommitItem item : items) {
result.add(item.path);
}
return result;
}
private void updateFileSectionText() {
filesSection.setText(MessageFormat.format(UIText.CommitDialog_Files,
Integer.valueOf(filesViewer.getCheckedElements().length),
Integer.valueOf(filesViewer.getTree().getItemCount())));
}
private IMenuListener createContextMenuListener() {
return new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
if (!allowToChangeSelection)
return;
final IStructuredSelection selection = (IStructuredSelection) filesViewer
.getSelection();
if (selection.isEmpty())
return;
if (selection.size() == 1
&& selection.getFirstElement() instanceof CommitItem) {
CommitItem commitItem = (CommitItem) selection
.getFirstElement();
manager.add(createCompareAction(commitItem));
}
manager.add(createAddAction(selection));
}
};
}
private Action createCompareAction(final CommitItem commitItem) {
return new Action(UIText.CommitDialog_CompareWithHeadRevision) {
@Override
public void run() {
compare(commitItem);
}
};
}
private Action createAddAction(final IStructuredSelection selection) {
return new Action(UIText.CommitDialog_AddFileOnDiskToIndex) {
public void run() {
AddCommand addCommand = new Git(repository).add();
for (Iterator<?> it = selection.iterator(); it.hasNext();) {
CommitItem commitItem = (CommitItem) it.next();
addCommand.addFilepattern(commitItem.path);
}
try {
addCommand.call();
} catch (Exception e) {
Activator.logError(UIText.CommitDialog_ErrorAddingFiles, e);
}
for (Iterator<?> it = selection.iterator(); it.hasNext();) {
CommitItem commitItem = (CommitItem) it.next();
try {
commitItem.status = getFileStatus(commitItem.path);
} catch (IOException e) {
Activator.logError(
UIText.CommitDialog_ErrorAddingFiles, e);
}
}
filesViewer.refresh(true);
}
};
}
/** Retrieve file status
* @param path
* @return file status
* @throws IOException
*/
private Status getFileStatus(String path) throws IOException {
AdaptableFileTreeIterator fileTreeIterator = new AdaptableFileTreeIterator(
repository, ResourcesPlugin.getWorkspace().getRoot());
IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, fileTreeIterator);
Set<String> repositoryPaths = Collections.singleton(path);
indexDiff.setFilter(PathFilterGroup.createFromStrings(repositoryPaths));
indexDiff.diff(null, 0, 0, ""); //$NON-NLS-1$
return getFileStatus(path, indexDiff);
}
/** Retrieve file status from an already calculated IndexDiff
* @param path
* @param indexDiff
* @return file status
*/
private static Status getFileStatus(String path, IndexDiff indexDiff) {
if (indexDiff.getAssumeUnchanged().contains(path)) {
return Status.ASSUME_UNCHANGED;
} else if (indexDiff.getAdded().contains(path)) {
// added
if (indexDiff.getModified().contains(path))
return Status.ADDED_INDEX_DIFF;
else
return Status.ADDED;
} else if (indexDiff.getChanged().contains(path)) {
// changed
if (indexDiff.getModified().contains(path))
return Status.MODIFIED_INDEX_DIFF;
else
return Status.MODIFIED;
} else if (indexDiff.getUntracked().contains(path)) {
// untracked
if (indexDiff.getRemoved().contains(path))
return Status.REMOVED_UNTRACKED;
else
return Status.UNTRACKED;
} else if (indexDiff.getRemoved().contains(path)) {
// removed
return Status.REMOVED;
} else if (indexDiff.getMissing().contains(path)) {
// missing
return Status.REMOVED_NOT_STAGED;
} else if (indexDiff.getModified().contains(path)) {
// modified (and not changed!)
return Status.MODIFIED_NOT_STAGED;
}
return Status.UNKNOWN;
}
private static int getProblemSeverity(Repository repository, String path) {
IFile file = ResourceUtil.getFileForLocation(repository, path);
if (file != null) {
try {
int severity = file.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE);
return severity;
} catch (CoreException e) {
// Fall back to below
}
}
return IProblemDecoratable.SEVERITY_NONE;
}
@Override
protected void okPressed() {
if (!isCommitWithoutFilesAllowed()) {
MessageDialog.openWarning(getShell(), UIText.CommitDialog_ErrorNoItemsSelected, UIText.CommitDialog_ErrorNoItemsSelectedToBeCommitted);
return;
}
if (!commitMessageComponent.checkCommitInfo())
return;
Object[] checkedElements = filesViewer.getCheckedElements();
selectedFiles.clear();
for (Object obj : checkedElements)
selectedFiles.add(((CommitItem) obj).path);
amending = commitMessageComponent.isAmending();
commitMessage = commitMessageComponent.getCommitMessage();
author = commitMessageComponent.getAuthor();
committer = commitMessageComponent.getCommitter();
createChangeId = changeIdItem.getSelection();
IDialogSettings settings = org.eclipse.egit.ui.Activator
.getDefault().getDialogSettings();
settings.put(SHOW_UNTRACKED_PREF, showUntracked);
CommitMessageHistory.saveCommitHistory(getCommitMessage());
super.okPressed();
}
@Override
protected int getShellStyle() {
return super.getShellStyle() | SWT.RESIZE;
}
private void compare(CommitItem commitItem) {
IFile file = findFile(commitItem.path);
if (file == null
|| RepositoryProvider.getProvider(file.getProject()) == null)
CompareUtils
.compareHeadWithWorkingTree(repository, commitItem.path);
else
CompareUtils.compareHeadWithWorkspace(repository, file);
}
private IFile findFile(String path) {
URI uri = new File(repository.getWorkTree(), path).toURI();
IFile[] workspaceFiles = ResourcesPlugin.getWorkspace().getRoot()
.findFilesForLocationURI(uri);
if (workspaceFiles.length > 0)
return workspaceFiles[0];
else
return null;
}
}
class CommitItem implements IProblemDecoratable {
Status status;
String path;
boolean submodule;
int problemSeverity;
public int getProblemSeverity() {
return problemSeverity;
}
/** The ordinal of this {@link Enum} is used to provide the "native" sorting of the list */
public static enum Status {
/** */
ADDED(UIText.CommitDialog_StatusAdded),
/** */
MODIFIED(UIText.CommitDialog_StatusModified),
/** */
REMOVED(UIText.CommitDialog_StatusRemoved),
/** */
ADDED_INDEX_DIFF(UIText.CommitDialog_StatusAddedIndexDiff),
/** */
MODIFIED_INDEX_DIFF(UIText.CommitDialog_StatusModifiedIndexDiff),
/** */
MODIFIED_NOT_STAGED(UIText.CommitDialog_StatusModifiedNotStaged),
/** */
REMOVED_NOT_STAGED(UIText.CommitDialog_StatusRemovedNotStaged),
/** */
UNTRACKED(UIText.CommitDialog_StatusUntracked),
/** */
REMOVED_UNTRACKED(UIText.CommitDialog_StatusRemovedUntracked),
/** */
ASSUME_UNCHANGED(UIText.CommitDialog_StatusAssumeUnchaged),
/** */
UNKNOWN(UIText.CommitDialog_StatusUnknown);
public String getText() {
return myText;
}
private final String myText;
private Status(String text) {
myText = text;
}
}
public static enum Order implements Comparator<CommitItem> {
ByStatus() {
public int compare(CommitItem o1, CommitItem o2) {
return o1.status.compareTo(o2.status);
}
},
ByFile() {
public int compare(CommitItem o1, CommitItem o2) {
return o1.path.compareTo(
o2.path);
}
};
public Comparator<CommitItem> ascending() {
return this;
}
public Comparator<CommitItem> descending() {
return Collections.reverseOrder(this);
}
}
}
class CommitViewerComparator extends ViewerComparator {
public CommitViewerComparator(Comparator comparator){
super(comparator);
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
return getComparator().compare(e1, e2);
}
}
| Use ResourceUtil for finding IFile for compare in commit dialog
ResourceUtil correctly handles the case where the resource is not shared
by the Git team provider.
Bug: 42182
Change-Id: I3c19ef170161b6084dbf7a12943b6b9ac5bb6310
Signed-off-by: Robin Stocker <[email protected]>
| org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/dialogs/CommitDialog.java | Use ResourceUtil for finding IFile for compare in commit dialog | <ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/dialogs/CommitDialog.java
<ide> *******************************************************************************/
<ide> package org.eclipse.egit.ui.internal.dialogs;
<ide>
<del>import java.io.File;
<ide> import java.io.IOException;
<del>import java.net.URI;
<ide> import java.text.MessageFormat;
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<ide> }
<ide>
<ide> private IFile findFile(String path) {
<del> URI uri = new File(repository.getWorkTree(), path).toURI();
<del> IFile[] workspaceFiles = ResourcesPlugin.getWorkspace().getRoot()
<del> .findFilesForLocationURI(uri);
<del> if (workspaceFiles.length > 0)
<del> return workspaceFiles[0];
<del> else
<del> return null;
<add> return ResourceUtil.getFileForLocation(repository, path);
<ide> }
<ide> }
<ide> |
|
Java | epl-1.0 | 5eacce0cc44bfbc21b9da223f439e72bb7352aeb | 0 | Fiser12/Redes-Invernadero | package servidor.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import javax.swing.SwingConstants;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
public class ventanaServidor extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ventanaServidor frame = new ventanaServidor();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ventanaServidor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panelSuperior = new JPanel();
contentPane.add(panelSuperior, BorderLayout.NORTH);
panelSuperior.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblS = new JLabel("Seleccionar una opcion:");
panelSuperior.add(lblS);
JPanel panelcentral = new JPanel();
contentPane.add(panelcentral, BorderLayout.CENTER);
panelcentral.setLayout(new CardLayout(0, 0));
JPanel botoneraInicial = new JPanel();
panelcentral.add(botoneraInicial, "name_117604164092399");
botoneraInicial.setLayout(new GridLayout(2, 2, 0, 0));
JPanel panelAU = new JPanel();
botoneraInicial.add(panelAU);
panelAU.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAUsuarios = new JButton("Administrar usuarios");
panelAU.add(btnAUsuarios);
JPanel panelAP = new JPanel();
botoneraInicial.add(panelAP);
JButton btnPlacas = new JButton("Administrar Placas");
panelAP.add(btnPlacas);
JPanel panelAs = new JPanel();
botoneraInicial.add(panelAs);
JButton btnASensores = new JButton("Administrar Sensores");
panelAs.add(btnASensores);
JPanel panelAd = new JPanel();
botoneraInicial.add(panelAd);
JButton btnAVariables = new JButton("Administrar Variables");
btnAVariables.setHorizontalAlignment(SwingConstants.RIGHT);
panelAd.add(btnAVariables);
JPanel panelUsuarios = new JPanel();
panelcentral.add(panelUsuarios, "name_117609091157597");
panelUsuarios.setLayout(new BorderLayout(0, 0));
JPanel panelBotonesUsuario = new JPanel();
panelUsuarios.add(panelBotonesUsuario);
JButton btnAUsuarioPlaca = new JButton("Asociciar Usuarios a placas");
JButton btnFUsuario = new JButton("Funcionalidades de usuario");
panelBotonesUsuario.setLayout(new GridLayout(3, 1, 0, 0));
panelBotonesUsuario.add(btnAUsuarioPlaca);
panelBotonesUsuario.add(btnFUsuario);
JButton btnCUsuario = new JButton("Crear Usuario");
panelBotonesUsuario.add(btnCUsuario);
JButton btnAtras = new JButton("Atras");
panelUsuarios.add(btnAtras, BorderLayout.SOUTH);
JPanel panelPlacas = new JPanel();
panelcentral.add(panelPlacas, "name_119314737616723");
panelPlacas.setLayout(new BorderLayout(0, 0));
JPanel panelCPlacas = new JPanel();
panelPlacas.add(panelCPlacas, BorderLayout.CENTER);
panelCPlacas.setLayout(new GridLayout(0, 1, 0, 0));
JButton btnLPlaca = new JButton("Lista de Placas");
panelCPlacas.add(btnLPlaca);
JButton btnCPlaca = new JButton("Crear placa");
panelCPlacas.add(btnCPlaca);
JPanel panelAtras = new JPanel();
panelPlacas.add(panelAtras, BorderLayout.SOUTH);
panelAtras.setLayout(new GridLayout(0, 1, 0, 0));
JButton btnAtras1 = new JButton("Atras");
panelAtras.add(btnAtras1);
JPanel panelSensores = new JPanel();
panelcentral.add(panelSensores, "name_120084261205515");
panelSensores.setLayout(new BorderLayout(0, 0));
JPanel panelCSensores = new JPanel();
panelSensores.add(panelCSensores, BorderLayout.CENTER);
panelCSensores.setLayout(new GridLayout(0, 1, 0, 0));
JButton btnLSensores = new JButton("Lista de sensores");
panelCSensores.add(btnLSensores);
JButton btnCSensor = new JButton("Crear Sensor");
panelCSensores.add(btnCSensor);
JButton btnNewButton_1 = new JButton("Asocciar sensores a placas");
panelCSensores.add(btnNewButton_1);
JPanel panelAtras2 = new JPanel();
panelSensores.add(panelAtras2, BorderLayout.SOUTH);
panelAtras2.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnAtras2 = new JButton("Atras");
panelAtras2.add(btnAtras2);
JPanel panelVariables = new JPanel();
panelcentral.add(panelVariables, "name_120457173488400");
panelVariables.setLayout(new BorderLayout(0, 0));
JPanel panelCVariables = new JPanel();
panelVariables.add(panelCVariables, BorderLayout.CENTER);
panelCVariables.setLayout(new GridLayout(3, 1, 0, 0));
JButton btnLVariables = new JButton("Lista de Variables");
panelCVariables.add(btnLVariables);
JButton btnAVPlacas = new JButton("Asocciar variables a las placas");
panelCVariables.add(btnAVPlacas);
JButton btnCVariable = new JButton("Crear Variable");
panelCVariables.add(btnCVariable);
JPanel panelAtras3 = new JPanel();
panelVariables.add(panelAtras3, BorderLayout.SOUTH);
panelAtras3.setLayout(new GridLayout(0, 1, 0, 0));
JButton btnAtras3 = new JButton("Atras");
panelAtras3.add(btnAtras3);
JPanel panelApagar = new JPanel();
contentPane.add(panelApagar, BorderLayout.SOUTH);
JButton btnConexiones = new JButton("Administrar conexiones");
panelApagar.add(btnConexiones);
JButton btnAServidor = new JButton("Apagar servidor");
panelApagar.add(btnAServidor);
}
}
| src/servidor/view/ventanaServidor.java | package servidor.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JTextPane;
public class ventanaServidor extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ventanaServidor frame = new ventanaServidor();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ventanaServidor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new GridLayout(0, 2, 0, 0));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2);
JButton btnNewButton = new JButton("New button");
panel_2.add(btnNewButton);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3);
JButton btnNewButton_1 = new JButton("New button");
panel_3.add(btnNewButton_1);
}
}
| Ventana Servidor sin tablas | src/servidor/view/ventanaServidor.java | Ventana Servidor sin tablas | <ide><path>rc/servidor/view/ventanaServidor.java
<ide> import java.awt.GridLayout;
<ide> import javax.swing.JButton;
<ide> import javax.swing.JTextPane;
<add>import javax.swing.JLabel;
<add>import java.awt.FlowLayout;
<add>import java.awt.CardLayout;
<add>import javax.swing.SwingConstants;
<add>import javax.swing.GroupLayout;
<add>import javax.swing.GroupLayout.Alignment;
<ide>
<ide> public class ventanaServidor extends JFrame {
<ide>
<ide> contentPane.setLayout(new BorderLayout(0, 0));
<ide> setContentPane(contentPane);
<ide>
<del> JPanel panel = new JPanel();
<del> contentPane.add(panel, BorderLayout.CENTER);
<add> JPanel panelSuperior = new JPanel();
<add> contentPane.add(panelSuperior, BorderLayout.NORTH);
<add> panelSuperior.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
<ide>
<del> JPanel panel_1 = new JPanel();
<del> contentPane.add(panel_1, BorderLayout.SOUTH);
<del> panel_1.setLayout(new GridLayout(0, 2, 0, 0));
<add> JLabel lblS = new JLabel("Seleccionar una opcion:");
<add> panelSuperior.add(lblS);
<ide>
<del> JPanel panel_2 = new JPanel();
<del> panel_1.add(panel_2);
<add> JPanel panelcentral = new JPanel();
<add> contentPane.add(panelcentral, BorderLayout.CENTER);
<add> panelcentral.setLayout(new CardLayout(0, 0));
<ide>
<del> JButton btnNewButton = new JButton("New button");
<del> panel_2.add(btnNewButton);
<add> JPanel botoneraInicial = new JPanel();
<add> panelcentral.add(botoneraInicial, "name_117604164092399");
<add> botoneraInicial.setLayout(new GridLayout(2, 2, 0, 0));
<ide>
<del> JPanel panel_3 = new JPanel();
<del> panel_1.add(panel_3);
<add> JPanel panelAU = new JPanel();
<add> botoneraInicial.add(panelAU);
<add> panelAU.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
<ide>
<del> JButton btnNewButton_1 = new JButton("New button");
<del> panel_3.add(btnNewButton_1);
<add> JButton btnAUsuarios = new JButton("Administrar usuarios");
<add> panelAU.add(btnAUsuarios);
<add>
<add> JPanel panelAP = new JPanel();
<add> botoneraInicial.add(panelAP);
<add>
<add> JButton btnPlacas = new JButton("Administrar Placas");
<add> panelAP.add(btnPlacas);
<add>
<add> JPanel panelAs = new JPanel();
<add> botoneraInicial.add(panelAs);
<add>
<add> JButton btnASensores = new JButton("Administrar Sensores");
<add> panelAs.add(btnASensores);
<add>
<add> JPanel panelAd = new JPanel();
<add> botoneraInicial.add(panelAd);
<add>
<add> JButton btnAVariables = new JButton("Administrar Variables");
<add> btnAVariables.setHorizontalAlignment(SwingConstants.RIGHT);
<add> panelAd.add(btnAVariables);
<add>
<add> JPanel panelUsuarios = new JPanel();
<add> panelcentral.add(panelUsuarios, "name_117609091157597");
<add> panelUsuarios.setLayout(new BorderLayout(0, 0));
<add>
<add> JPanel panelBotonesUsuario = new JPanel();
<add> panelUsuarios.add(panelBotonesUsuario);
<add>
<add> JButton btnAUsuarioPlaca = new JButton("Asociciar Usuarios a placas");
<add>
<add> JButton btnFUsuario = new JButton("Funcionalidades de usuario");
<add> panelBotonesUsuario.setLayout(new GridLayout(3, 1, 0, 0));
<add> panelBotonesUsuario.add(btnAUsuarioPlaca);
<add> panelBotonesUsuario.add(btnFUsuario);
<add>
<add> JButton btnCUsuario = new JButton("Crear Usuario");
<add> panelBotonesUsuario.add(btnCUsuario);
<add>
<add> JButton btnAtras = new JButton("Atras");
<add> panelUsuarios.add(btnAtras, BorderLayout.SOUTH);
<add>
<add> JPanel panelPlacas = new JPanel();
<add> panelcentral.add(panelPlacas, "name_119314737616723");
<add> panelPlacas.setLayout(new BorderLayout(0, 0));
<add>
<add> JPanel panelCPlacas = new JPanel();
<add> panelPlacas.add(panelCPlacas, BorderLayout.CENTER);
<add> panelCPlacas.setLayout(new GridLayout(0, 1, 0, 0));
<add>
<add> JButton btnLPlaca = new JButton("Lista de Placas");
<add> panelCPlacas.add(btnLPlaca);
<add>
<add> JButton btnCPlaca = new JButton("Crear placa");
<add> panelCPlacas.add(btnCPlaca);
<add>
<add> JPanel panelAtras = new JPanel();
<add> panelPlacas.add(panelAtras, BorderLayout.SOUTH);
<add> panelAtras.setLayout(new GridLayout(0, 1, 0, 0));
<add>
<add> JButton btnAtras1 = new JButton("Atras");
<add> panelAtras.add(btnAtras1);
<add>
<add> JPanel panelSensores = new JPanel();
<add> panelcentral.add(panelSensores, "name_120084261205515");
<add> panelSensores.setLayout(new BorderLayout(0, 0));
<add>
<add> JPanel panelCSensores = new JPanel();
<add> panelSensores.add(panelCSensores, BorderLayout.CENTER);
<add> panelCSensores.setLayout(new GridLayout(0, 1, 0, 0));
<add>
<add> JButton btnLSensores = new JButton("Lista de sensores");
<add> panelCSensores.add(btnLSensores);
<add>
<add> JButton btnCSensor = new JButton("Crear Sensor");
<add> panelCSensores.add(btnCSensor);
<add>
<add> JButton btnNewButton_1 = new JButton("Asocciar sensores a placas");
<add> panelCSensores.add(btnNewButton_1);
<add>
<add> JPanel panelAtras2 = new JPanel();
<add> panelSensores.add(panelAtras2, BorderLayout.SOUTH);
<add> panelAtras2.setLayout(new GridLayout(1, 0, 0, 0));
<add>
<add> JButton btnAtras2 = new JButton("Atras");
<add> panelAtras2.add(btnAtras2);
<add>
<add> JPanel panelVariables = new JPanel();
<add> panelcentral.add(panelVariables, "name_120457173488400");
<add> panelVariables.setLayout(new BorderLayout(0, 0));
<add>
<add> JPanel panelCVariables = new JPanel();
<add> panelVariables.add(panelCVariables, BorderLayout.CENTER);
<add> panelCVariables.setLayout(new GridLayout(3, 1, 0, 0));
<add>
<add> JButton btnLVariables = new JButton("Lista de Variables");
<add> panelCVariables.add(btnLVariables);
<add>
<add> JButton btnAVPlacas = new JButton("Asocciar variables a las placas");
<add> panelCVariables.add(btnAVPlacas);
<add>
<add> JButton btnCVariable = new JButton("Crear Variable");
<add> panelCVariables.add(btnCVariable);
<add>
<add> JPanel panelAtras3 = new JPanel();
<add> panelVariables.add(panelAtras3, BorderLayout.SOUTH);
<add> panelAtras3.setLayout(new GridLayout(0, 1, 0, 0));
<add>
<add> JButton btnAtras3 = new JButton("Atras");
<add> panelAtras3.add(btnAtras3);
<add>
<add> JPanel panelApagar = new JPanel();
<add> contentPane.add(panelApagar, BorderLayout.SOUTH);
<add>
<add> JButton btnConexiones = new JButton("Administrar conexiones");
<add> panelApagar.add(btnConexiones);
<add>
<add> JButton btnAServidor = new JButton("Apagar servidor");
<add> panelApagar.add(btnAServidor);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 385222ef2c197074a229a05ffd6fcb1497f94b7f | 0 | wschaeferB/autopsy,millmanorama/autopsy,millmanorama/autopsy,millmanorama/autopsy,wschaeferB/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,millmanorama/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilessearch;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.netbeans.junit.NbTestCase;
import org.openide.util.Exceptions;
import org.python.icu.impl.Assert;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.ImageDSProcessor;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.commonfilesearch.AbstractCommonAttributeInstance;
import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeSearchResults;
import org.sleuthkit.autopsy.commonfilesearch.DataSourceLoader;
import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeValue;
import org.sleuthkit.autopsy.testutils.CaseUtils;
import org.sleuthkit.autopsy.testutils.IngestUtils;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.TskCoreException;
/**
*
* Provides setup and utility for testing presence of files in different data
* sets discoverable by Common Files Features.
*
* Data set definitions:
*
* set 1
* + file1
* - IMG_6175.jpg
* + file2
* - IMG_6175.jpg
* + file3
* - BasicStyleGuide.doc
*
* set 2
* - adsf.pdf
* - IMG_6175.jpg
*
* set 3
* - BasicStyleGuide.doc
* - IMG_6175.jpg
*
* set 4
* - file.dat (empty file)
*/
class IntraCaseTestUtils {
private static final String CASE_NAME = "IntraCaseCommonFilesSearchTest";
static final Path CASE_DIRECTORY_PATH = Paths.get(System.getProperty("java.io.tmpdir"), CASE_NAME);
private final Path imagePath1;
private final Path imagePath2;
private final Path imagePath3;
private final Path imagePath4;
static final String IMG = "IMG_6175.jpg";
static final String DOC = "BasicStyleGuide.doc";
static final String PDF = "adsf.pdf"; //not a typo - it appears this way in the test image
static final String EMPTY = "file.dat";
static final String SET1 = "CommonFiles_img1_v1.vhd";
static final String SET2 = "CommonFiles_img2_v1.vhd";
static final String SET3 = "CommonFiles_img3_v1.vhd";
static final String SET4 = "CommonFiles_img4_v1.vhd";
private final DataSourceLoader dataSourceLoader;
private final String caseName;
IntraCaseTestUtils(NbTestCase nbTestCase, String caseName){
this.imagePath1 = Paths.get(nbTestCase.getDataDir().toString(), SET1);
this.imagePath2 = Paths.get(nbTestCase.getDataDir().toString(), SET2);
this.imagePath3 = Paths.get(nbTestCase.getDataDir().toString(), SET3);
this.imagePath4 = Paths.get(nbTestCase.getDataDir().toString(), SET4);
this.dataSourceLoader = new DataSourceLoader();
this.caseName = caseName;
}
void setUp() {
this.createAsCurrentCase();
final ImageDSProcessor imageDSProcessor = new ImageDSProcessor();
this.addImageOne(imageDSProcessor);
this.addImageTwo(imageDSProcessor);
this.addImageThree(imageDSProcessor);
this.addImageFour(imageDSProcessor);
}
void addImageFour(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath4);
}
void addImageThree(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath3);
}
void addImageTwo(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath2);
}
void addImageOne(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath1);
}
void createAsCurrentCase() {
CaseUtils.createAsCurrentCase(this.caseName);
}
Map<Long, String> getDataSourceMap() throws NoCurrentCaseException, TskCoreException, SQLException {
return this.dataSourceLoader.getDataSourceMap();
}
void tearDown() {
CaseUtils.closeCurrentCase(false);
try {
CaseUtils.deleteCaseDir(CASE_DIRECTORY_PATH.toFile());
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
//does not represent a failure in the common files search feature
}
}
/**
* Verify that the given file appears a precise number times in the given
* data source.
*
* @param searchDomain search domain
* @param objectIdToDataSourceMap mapping of file ids to data source names
* @param fileName name of file to search for
* @param dataSource name of data source where file should appear
* @param instanceCount number of appearances of the given file
* @return true if a file with the given name exists the specified number of
* times in the given data source
*/
static boolean verifyInstanceExistanceAndCount(List<AbstractFile> searchDomain, Map<Long, String> objectIdToDataSourceMap, String fileName, String dataSource, int instanceCount) {
int tally = 0;
for (AbstractFile file : searchDomain) {
Long objectId = file.getId();
String name = file.getName();
String dataSourceName = objectIdToDataSourceMap.get(objectId);
if (name.toLowerCase().equals(fileName.toLowerCase()) && dataSourceName.toLowerCase().equals(dataSource.toLowerCase())) {
tally++;
}
}
return tally == instanceCount;
}
/**
* Convenience method which verifies that a file exists within a given data
* source exactly once.
*
* @param files search domain
* @param objectIdToDataSource mapping of file ids to data source names
* @param name name of file to search for
* @param dataSource name of data source where file should appear
* @return true if a file with the given name exists once in the given data
* source
*/
static boolean verifySingularInstanceExistance(List<AbstractFile> files, Map<Long, String> objectIdToDataSource, String name, String dataSource) {
return verifyInstanceExistanceAndCount(files, objectIdToDataSource, name, dataSource, 1);
}
/**
* Create a convenience lookup table mapping file instance object ids to
* the data source they appear in.
*
* @param metadata object returned by the code under test
* @return mapping of objectId to data source name
*/
static Map<Long, String> mapFileInstancesToDataSources(CommonAttributeSearchResults metadata) {
Map<Long, String> instanceIdToDataSource = new HashMap<>();
for (Map.Entry<Integer, List<CommonAttributeValue>> entry : metadata.getMetadata().entrySet()) {
for (CommonAttributeValue md : entry.getValue()) {
for (AbstractCommonAttributeInstance fim : md.getInstances()) {
instanceIdToDataSource.put(fim.getAbstractFileObjectId(), fim.getDataSource());
}
}
}
return instanceIdToDataSource;
}
static List<AbstractFile> getFiles(Set<Long> objectIds) {
List<AbstractFile> files = new ArrayList<>(objectIds.size());
for (Long id : objectIds) {
try {
AbstractFile file = Case.getCurrentCaseThrows().getSleuthkitCase().getAbstractFileById(id);
files.add(file);
} catch (NoCurrentCaseException | TskCoreException ex) {
Exceptions.printStackTrace(ex);
Assert.fail(ex);
}
}
return files;
}
static Long getDataSourceIdByName(String name, Map<Long, String> dataSources) {
if (dataSources.containsValue(name)) {
for (Map.Entry<Long, String> dataSource : dataSources.entrySet()) {
if (dataSource.getValue().equals(name)) {
return dataSource.getKey();
}
}
} else {
throw new IndexOutOfBoundsException(String.format("Name should be one of: {0}", String.join(",", dataSources.values())));
}
return null;
}
}
| Core/test/qa-functional/src/org/sleuthkit/autopsy/commonfilessearch/IntraCaseTestUtils.java | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilessearch;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.netbeans.junit.NbTestCase;
import org.openide.util.Exceptions;
import org.python.icu.impl.Assert;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.ImageDSProcessor;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.commonfilesearch.AbstractCommonAttributeInstance;
import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeSearchResults;
import org.sleuthkit.autopsy.commonfilesearch.DataSourceLoader;
import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeValue;
import org.sleuthkit.autopsy.testutils.CaseUtils;
import org.sleuthkit.autopsy.testutils.IngestUtils;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.TskCoreException;
/**
*
* Provides setup and utility for testing presence of files in different data
* sets discoverable by Common Files Features.
*
* Data set definitions:
*
* set 1
* + file1
* - IMG_6175.jpg
* + file2
* - IMG_6175.jpg
* + file3
* - BasicStyleGuide.doc
*
* set 2
* - adsf.pdf
* - IMG_6175.jpg
*
* set 3
* - BasicStyleGuide.doc
* - IMG_6175.jpg
*
* set 4
* - file.dat (empty file)
*/
class IntraCaseTestUtils {
private static final String CASE_NAME = "IntraCaseCommonFilesSearchTest";
static final Path CASE_DIRECTORY_PATH = Paths.get(System.getProperty("java.io.tmpdir"), CASE_NAME);
private final Path imagePath1;
private final Path imagePath2;
private final Path imagePath3;
private final Path imagePath4;
static final String IMG = "IMG_6175.jpg";
static final String DOC = "BasicStyleGuide.doc";
static final String PDF = "adsf.pdf"; //not a typo - it appears this way in the test image
static final String EMPTY = "file.dat";
static final String SET1 = "CommonFiles_img1_v1.vhd";
static final String SET2 = "CommonFiles_img2_v1.vhd";
static final String SET3 = "CommonFiles_img3_v1.vhd";
static final String SET4 = "CommonFiles_img4_v1.vhd";
private final DataSourceLoader dataSourceLoader;
private final String caseName;
IntraCaseTestUtils(NbTestCase nbTestCase, String caseName){
this.imagePath1 = Paths.get(nbTestCase.getDataDir().toString(), SET1);
this.imagePath2 = Paths.get(nbTestCase.getDataDir().toString(), SET2);
this.imagePath3 = Paths.get(nbTestCase.getDataDir().toString(), SET3);
this.imagePath4 = Paths.get(nbTestCase.getDataDir().toString(), SET4);
this.dataSourceLoader = new DataSourceLoader();
this.caseName = caseName;
}
void setUp() {
this.createAsCurrentCase();
final ImageDSProcessor imageDSProcessor = new ImageDSProcessor();
this.addImageOne(imageDSProcessor);
this.addImageTwo(imageDSProcessor);
this.addImageThree(imageDSProcessor);
this.addImageFour(imageDSProcessor);
}
void addImageFour(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath4);
}
void addImageThree(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath3);
}
void addImageTwo(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath2);
}
void addImageOne(final ImageDSProcessor imageDSProcessor) {
IngestUtils.addDataSource(imageDSProcessor, imagePath1);
}
void createAsCurrentCase() {
CaseUtils.createAsCurrentCase(this.caseName);
}
Map<Long, String> getDataSourceMap() throws NoCurrentCaseException, TskCoreException, SQLException {
return this.dataSourceLoader.getDataSourceMap();
}
void tearDown() {
CaseUtils.closeCurrentCase(false);
try {
CaseUtils.deleteCaseDir(CASE_DIRECTORY_PATH.toFile());
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
//does not represent a failure in the common files search feature
}
}
/**
* Verify that the given file appears a precise number times in the given
* data source.
*
* @param searchDomain search domain
* @param objectIdToDataSourceMap mapping of file ids to data source names
* @param fileName name of file to search for
* @param dataSource name of data source where file should appear
* @param instanceCount number of appearances of the given file
* @return true if a file with the given name exists the specified number of
* times in the given data source
*/
static boolean verifyInstanceExistanceAndCount(List<AbstractFile> searchDomain, Map<Long, String> objectIdToDataSourceMap, String fileName, String dataSource, int instanceCount) {
int tally = 0;
for (AbstractFile file : searchDomain) {
Long objectId = file.getId();
String name = file.getName();
String dataSourceName = objectIdToDataSourceMap.get(objectId);
if (name.equals(name) && dataSourceName.equals(dataSource)) {
tally++;
}
}
return tally == instanceCount;
}
/**
* Convenience method which verifies that a file exists within a given data
* source exactly once.
*
* @param files search domain
* @param objectIdToDataSource mapping of file ids to data source names
* @param name name of file to search for
* @param dataSource name of data source where file should appear
* @return true if a file with the given name exists once in the given data
* source
*/
static boolean verifySingularInstanceExistance(List<AbstractFile> files, Map<Long, String> objectIdToDataSource, String name, String dataSource) {
return verifyInstanceExistanceAndCount(files, objectIdToDataSource, name, dataSource, 1);
}
/**
* Create a convenience lookup table mapping file instance object ids to
* the data source they appear in.
*
* @param metadata object returned by the code under test
* @return mapping of objectId to data source name
*/
static Map<Long, String> mapFileInstancesToDataSources(CommonAttributeSearchResults metadata) {
Map<Long, String> instanceIdToDataSource = new HashMap<>();
for (Map.Entry<Integer, List<CommonAttributeValue>> entry : metadata.getMetadata().entrySet()) {
for (CommonAttributeValue md : entry.getValue()) {
for (AbstractCommonAttributeInstance fim : md.getInstances()) {
instanceIdToDataSource.put(fim.getAbstractFileObjectId(), fim.getDataSource());
}
}
}
return instanceIdToDataSource;
}
static List<AbstractFile> getFiles(Set<Long> objectIds) {
List<AbstractFile> files = new ArrayList<>(objectIds.size());
for (Long id : objectIds) {
try {
AbstractFile file = Case.getCurrentCaseThrows().getSleuthkitCase().getAbstractFileById(id);
files.add(file);
} catch (NoCurrentCaseException | TskCoreException ex) {
Exceptions.printStackTrace(ex);
Assert.fail(ex);
}
}
return files;
}
static Long getDataSourceIdByName(String name, Map<Long, String> dataSources) {
if (dataSources.containsValue(name)) {
for (Map.Entry<Long, String> dataSource : dataSources.entrySet()) {
if (dataSource.getValue().equals(name)) {
return dataSource.getKey();
}
}
} else {
throw new IndexOutOfBoundsException(String.format("Name should be one of: {0}", String.join(",", dataSources.values())));
}
return null;
}
}
| must convert to lower since thats what the normalizer does
| Core/test/qa-functional/src/org/sleuthkit/autopsy/commonfilessearch/IntraCaseTestUtils.java | must convert to lower since thats what the normalizer does | <ide><path>ore/test/qa-functional/src/org/sleuthkit/autopsy/commonfilessearch/IntraCaseTestUtils.java
<ide>
<ide> String dataSourceName = objectIdToDataSourceMap.get(objectId);
<ide>
<del> if (name.equals(name) && dataSourceName.equals(dataSource)) {
<add> if (name.toLowerCase().equals(fileName.toLowerCase()) && dataSourceName.toLowerCase().equals(dataSource.toLowerCase())) {
<ide> tally++;
<ide> }
<ide> } |
|
Java | agpl-3.0 | dfc2c8c69e0657aa875ba1063a39a5403dcefbae | 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 | cef6530e-2e5f-11e5-9284-b827eb9e62be | hello.java | cedca6e8-2e5f-11e5-9284-b827eb9e62be | cef6530e-2e5f-11e5-9284-b827eb9e62be | hello.java | cef6530e-2e5f-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>cedca6e8-2e5f-11e5-9284-b827eb9e62be
<add>cef6530e-2e5f-11e5-9284-b827eb9e62be |
|
JavaScript | mit | 31bd68da5a7d2432cdbd78d20ca86d29b2153888 | 0 | kabam-archived/kabam-plugin-my-profile | var fs = require('fs');
exports.routes = function(mwc){
mwc.app.get('/auth/myProfile',function(request,response){
if(request.user){
if (request.is('json')) {
response.json(request.user)
} else {
var parameters = {
'title': 'Edit your profile',
'useGoogle': true,
'useGithub': (mwc.config.passport && mwc.config.passport.GITHUB_CLIENT_ID && mwc.config.passport.GITHUB_CLIENT_SECRET),
'useTwitter': (mwc.config.passport && mwc.config.passport.TWITTER_CONSUMER_KEY && mwc.config.passport.TWITTER_CONSUMER_SECRET),
'useFacebook': (mwc.config.passport && mwc.config.passport.FACEBOOK_APP_ID && mwc.config.passport.FACEBOOK_APP_SECRET)
};
response.render('my',parameters);
}
} else {
response.send(400);
}
});
mwc.app.post('/auth/myProfile',function(request,response){
if(request.user){
var makeResponse = function (err){
if(request.is('json')){
if(err){
response.send(400);
} else {
response.send(201);
}
} else {
if(err){
request.flash('error',err.message);
} else {
request.flash('success','Profile is saved!');
}
response.redirect('back');
}
}
var fields =['firstName', 'lastName', 'skype'];
fields.map(function(p){
if(request.body[p]){
request.user[p]=request.body[p];
}
});
if(request.body.password1 && request.body.password2 && (request.body.password1 === request.body.password2)){
request.user.setPassword(request.body.password1, makeResponse);
} else {
request.user.save(makeResponse);
}
} else {
response.send(400);
}
});
}; | index.js | var fs = require('fs');
exports.routes = function(mwc){
mwc.app.get('/auth/myProfile',function(request,response){
if(request.user){
if (request.is('json')) {
response.json(request.user)
} else {
response.render('my',{title:'Edit your profile'});
}
} else {
response.send(400);
}
});
mwc.app.post('/auth/myProfile',function(request,response){
if(request.user){
var makeResponse = function (err){
if(request.is('json')){
if(err){
response.send(400);
} else {
response.send(201);
}
} else {
if(err){
request.flash('error',err.message);
} else {
request.flash('success','Profile is saved!');
}
response.redirect('back');
}
}
var fields =['firstName', 'lastName', 'skype'];
fields.map(function(p){
if(request.body[p]){
request.user[p]=request.body[p];
}
});
if(request.body.password1 && request.body.password2 && (request.body.password1 === request.body.password2)){
request.user.setPassword(request.body.password1, makeResponse);
} else {
request.user.save(makeResponse);
}
} else {
response.send(400);
}
});
}; | [feature] - providers integration
| index.js | [feature] - providers integration | <ide><path>ndex.js
<ide> if (request.is('json')) {
<ide> response.json(request.user)
<ide> } else {
<del> response.render('my',{title:'Edit your profile'});
<add> var parameters = {
<add> 'title': 'Edit your profile',
<add> 'useGoogle': true,
<add> 'useGithub': (mwc.config.passport && mwc.config.passport.GITHUB_CLIENT_ID && mwc.config.passport.GITHUB_CLIENT_SECRET),
<add> 'useTwitter': (mwc.config.passport && mwc.config.passport.TWITTER_CONSUMER_KEY && mwc.config.passport.TWITTER_CONSUMER_SECRET),
<add> 'useFacebook': (mwc.config.passport && mwc.config.passport.FACEBOOK_APP_ID && mwc.config.passport.FACEBOOK_APP_SECRET)
<add> };
<add> response.render('my',parameters);
<ide> }
<ide> } else {
<ide> response.send(400); |
|
Java | apache-2.0 | c2c022591f3ccff2214972fae060973d8734405b | 0 | CMPUT301W14T07/Team7Project,CMPUT301W14T07/Team7Project | /**a
* @author Michael Raypold
*/
package ca.ualberta.team7project.test;
import java.util.Date;
import ca.ualberta.team7project.MainActivity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.test.ActivityInstrumentationTestCase2;
public class useCaseValidation extends
ActivityInstrumentationTestCase2<MainActivity> {
public useCaseValidation(Class<MainActivity> name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
}
/**
* Test CreateIdentity use case
* @return void
*/
public void createIdentityTest() {
UserPersistenceModel user = new UserPersistenceMode();
UserModel newUser = null;
if(user.exists() == false) {
newUser = new UserModel("Bob");
}
else {
newUser = user.getUser();
}
assertNotNull("User should be created or already exist", newUser);
}
/**
* Test SetLocation use case
* @return void
*/
public void setLocationTest() {
UserPersistenceModel user = new UserPersistenceMode();
UserModel newUser = user.getUser();
// TODO https://developer.android.com/training/location/location-testing.html
newUser.setCurrentLocation();
assertNotNull("Users location should now be set", newUser.getCurrentLocation());
}
/**
* Test AddTopLevelComment use case
* @return void
*/
public void addTopLevelCommentTest() {
TopicModel topic = new TopicModel();
ThreadModel thread = new ThreadModel();
UserModel user = new UserModel();
// TODO Maybe have a helper class so we aren't creating a new user for each Test.
user.setName("Bob");
thread.setComment("This is my comment");
thread.setLocation();
thread.setAuthor(CommentAuthor author = new CommentAuthor(user));
topic.addThread(thread);
assertTrue("Comment is top level", topic.threads.contains(thread));
}
/**
* Test sortByRelevance use case
* @return void
*/
public void sortByRelevanceTest() {
// For the actual test, this topic needs to be populated.
TopicModel topic = new TopicModel();
Boolean ordered = true;
Integer lastScore = null;
topic.sortThreadsByRelevance();
lastScore = topic.threads.get(0).getVotes();
for(Thread t : topic.getThreads()) {
if(lastScore < t.getVotes()) {
ordered = false;
break;
}
lastScore = t.getVotes();
}
assertTrue("Comments should be ordered by vote count", ordered);
}
/**
* Test DefaultCommentOrder use case
* <p>
* Comments are ordered based off date by default if the user has never seen the topic before
* @ return void
*/
public void defaultCommentOrderTest() {
// For the actual test, this topic needs to be populated.
TopicModel topic = new TopicModel();
Boolean ordered = true;
Date lastDate = null;
lastDate = topic.threads.get(0).getDate();
for(Thread t : topic.getThreads()) {
if(lastDate.compareTo(t.getDate()) < 0 ) {
ordered = false;
break;
}
lastDate = t.getDate();
}
assertTrue("Threads ordered by date", ordered);
}
}
| Team7ProjectTest/src/ca/ualberta/team7project/test/useCaseValidation.java | /**a
* @author Michael Raypold
*
*/
package ca.ualberta.team7project.test;
import ca.ualberta.team7project.MainActivity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.test.ActivityInstrumentationTestCase2;
public class useCaseValidation extends
ActivityInstrumentationTestCase2<MainActivity> {
public useCaseValidation(Class<MainActivity> name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
}
/**
* Test to check use case 1 (CreateIdentity)
*/
public void createIdentityTest() {
UserPersistenceModel user = new UserPersistenceMode();
UserModel newUser = null;
if(user.exists() == false) {
newUser = new UserModel("Bob");
}
else {
// Retrieve the user tied to the application
newUser = user.getUser();
}
assertNotNull("User should be created or already exist", newUser);
}
/**
* Test to check use case 2 (SetLocation)
*/
public void setLocationTest() {
UserPersistenceModel user = new UserPersistenceMode();
UserModel newUser = user.getUser();
// TODO https://developer.android.com/training/location/location-testing.html
newUser.setCurrentLocation();
assertNotNull("Users location should now be set", newUser.getCurrentLocation());
}
/**
* Test to check use case 11 (AddTopLevelComment)
*/
public void addTopLevelCommentTest() {
TopicModel topic = new TopicModel();
ThreadModel thread = new ThreadModel();
UserModel user = new UserModel();
// TODO Maybe have a helper class so we aren't creating a new user for each Test.
user.setName("Bob");
thread.setComment("This is my comment");
thread.setLocation();
thread.setAuthor(CommentAuthor author = new CommentAuthor(user));
topic.addThread(thread);
assertTrue("Comment is top level", topic.threads.contains(thread));
}
/**
*
*/
}
| More test cases
| Team7ProjectTest/src/ca/ualberta/team7project/test/useCaseValidation.java | More test cases | <ide><path>eam7ProjectTest/src/ca/ualberta/team7project/test/useCaseValidation.java
<ide> /**a
<ide> * @author Michael Raypold
<del> *
<ide> */
<ide> package ca.ualberta.team7project.test;
<add>
<add>import java.util.Date;
<ide>
<ide> import ca.ualberta.team7project.MainActivity;
<ide> import android.content.Context;
<ide> }
<ide>
<ide> /**
<del> * Test to check use case 1 (CreateIdentity)
<add> * Test CreateIdentity use case
<add> * @return void
<ide> */
<ide> public void createIdentityTest() {
<ide> UserPersistenceModel user = new UserPersistenceMode();
<ide> newUser = new UserModel("Bob");
<ide> }
<ide> else {
<del> // Retrieve the user tied to the application
<ide> newUser = user.getUser();
<ide> }
<ide>
<ide> }
<ide>
<ide> /**
<del> * Test to check use case 2 (SetLocation)
<add> * Test SetLocation use case
<add> * @return void
<ide> */
<ide> public void setLocationTest() {
<ide> UserPersistenceModel user = new UserPersistenceMode();
<ide> }
<ide>
<ide> /**
<del> * Test to check use case 11 (AddTopLevelComment)
<add> * Test AddTopLevelComment use case
<add> * @return void
<ide> */
<ide> public void addTopLevelCommentTest() {
<ide> TopicModel topic = new TopicModel();
<ide> }
<ide>
<ide> /**
<del> *
<add> * Test sortByRelevance use case
<add> * @return void
<ide> */
<add> public void sortByRelevanceTest() {
<add> // For the actual test, this topic needs to be populated.
<add> TopicModel topic = new TopicModel();
<add> Boolean ordered = true;
<add> Integer lastScore = null;
<add>
<add> topic.sortThreadsByRelevance();
<add> lastScore = topic.threads.get(0).getVotes();
<add>
<add> for(Thread t : topic.getThreads()) {
<add> if(lastScore < t.getVotes()) {
<add> ordered = false;
<add> break;
<add> }
<add>
<add> lastScore = t.getVotes();
<add> }
<ide>
<add> assertTrue("Comments should be ordered by vote count", ordered);
<add> }
<add>
<add> /**
<add> * Test DefaultCommentOrder use case
<add> * <p>
<add> * Comments are ordered based off date by default if the user has never seen the topic before
<add> * @ return void
<add> */
<add> public void defaultCommentOrderTest() {
<add> // For the actual test, this topic needs to be populated.
<add> TopicModel topic = new TopicModel();
<add> Boolean ordered = true;
<add> Date lastDate = null;
<add>
<add> lastDate = topic.threads.get(0).getDate();
<add>
<add> for(Thread t : topic.getThreads()) {
<add> if(lastDate.compareTo(t.getDate()) < 0 ) {
<add> ordered = false;
<add> break;
<add> }
<add>
<add> lastDate = t.getDate();
<add> }
<add>
<add> assertTrue("Threads ordered by date", ordered);
<add> }
<ide>
<ide> } |
|
Java | mit | a72d1d7071c866f673d889b9ded366f61acbba81 | 0 | Innovimax-SARL/mix-them | package innovimax.mixthem.operation;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.io.DefaultByteWriter;
import innovimax.mixthem.io.IByteOutput;
import innovimax.mixthem.io.IMultiChannelByteInput;
import innovimax.mixthem.io.InputResource;
import innovimax.mixthem.io.MultiChannelByteReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* <p>Abstract class for all byte operation.</p>
* @see IByteOperation
* @author Innovimax
* @version 1.0
*/
public abstract class AbstractByteOperation extends AbstractOperation implements IByteOperation {
/**
* Constructor
* @param params The list of parameters (maybe empty)
* @see innovimax.mixthem.arguments.RuleParam
* @see innovimax.mixthem.arguments.ParamValue
*/
public AbstractByteOperation(final Map<RuleParam, ParamValue> params) {
super(params);
}
@Override
public void processFiles(final List<InputResource> inputs, final OutputStream output) throws MixException, IOException {
final IMultiChannelByteInput reader = new MultiChannelByteReader(inputs);
final IByteOutput writer = new DefaultByteWriter(output);
final ByteResult result = new ByteResult();
while (reader.hasByte()) {
final byte[] byteRange = reader.nextByteRange();
process(byteRange, result);
if (result.hasResult()) {
result.getResult().forEach(i -> {
try {
writer.writeByte((byte) i);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
reader.close();
writer.close();
}
}
| src/main/java/innovimax/mixthem/operation/AbstractByteOperation.java | package innovimax.mixthem.operation;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.io.DefaultByteWriter;
import innovimax.mixthem.io.IByteOutput;
import innovimax.mixthem.io.IMultiChannelByteInput;
import innovimax.mixthem.io.InputResource;
import innovimax.mixthem.io.MultiChannelByteReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* <p>Abstract class for all byte operation.</p>
* @see IByteOperation
* @author Innovimax
* @version 1.0
*/
public abstract class AbstractByteOperation extends AbstractOperation implements IByteOperation {
/**
* Constructor
* @param params The list of parameters (maybe empty)
* @see innovimax.mixthem.arguments.RuleParam
* @see innovimax.mixthem.arguments.ParamValue
*/
public AbstractByteOperation(final Map<RuleParam, ParamValue> params) {
super(params);
}
@Override
public void processFiles(final List<InputResource> inputs, final OutputStream output) throws MixException, IOException {
final IMultiChannelByteInput reader = new MultiChannelByteReader(inputs);
final IByteOutput writer = new DefaultByteWriter(output);
final ByteResult result = new ByteResult();
while (reader.hasByte()) {
final byte[] bytes = reader.nextBytes();
process(bytes, result);
if (result.hasResult()) {
result.getResult().forEach(i -> {
try {
writer.writeByte((byte) i);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
reader.close();
writer.close();
}
}
| Update AbstractByteOperation.java | src/main/java/innovimax/mixthem/operation/AbstractByteOperation.java | Update AbstractByteOperation.java | <ide><path>rc/main/java/innovimax/mixthem/operation/AbstractByteOperation.java
<ide> final IByteOutput writer = new DefaultByteWriter(output);
<ide> final ByteResult result = new ByteResult();
<ide> while (reader.hasByte()) {
<del> final byte[] bytes = reader.nextBytes();
<del> process(bytes, result);
<add> final byte[] byteRange = reader.nextByteRange();
<add> process(byteRange, result);
<ide> if (result.hasResult()) {
<ide> result.getResult().forEach(i -> {
<ide> try { |
|
Java | apache-2.0 | efb15ea27ab66d477001ffc742fa9d75685df91a | 0 | FasterXML/jackson-databind,FasterXML/jackson-databind | package com.fasterxml.jackson.databind.deser.std;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.CompactStringObjectMap;
import com.fasterxml.jackson.databind.util.EnumResolver;
/**
* Deserializer class that can deserialize instances of
* specified Enum class from Strings and Integers.
*/
@JacksonStdImpl // was missing until 2.6
public class EnumDeserializer
extends StdScalarDeserializer<Object>
implements ContextualDeserializer
{
private static final long serialVersionUID = 1L;
protected Object[] _enumsByIndex;
/**
* @since 2.8
*/
private final Enum<?> _enumDefaultValue;
/**
* @since 2.7.3
*/
protected final CompactStringObjectMap _lookupByName;
/**
* Alternatively, we may need a different lookup object if "use toString"
* is defined.
*
* @since 2.7.3
*/
protected CompactStringObjectMap _lookupByToString;
protected final Boolean _caseInsensitive;
/**
* @since 2.9
*/
public EnumDeserializer(EnumResolver byNameResolver, Boolean caseInsensitive)
{
super(byNameResolver.getEnumClass());
_lookupByName = byNameResolver.constructLookup();
_enumsByIndex = byNameResolver.getRawEnums();
_enumDefaultValue = byNameResolver.getDefaultValue();
_caseInsensitive = caseInsensitive;
}
/**
* @since 2.9
*/
protected EnumDeserializer(EnumDeserializer base, Boolean caseInsensitive)
{
super(base);
_lookupByName = base._lookupByName;
_enumsByIndex = base._enumsByIndex;
_enumDefaultValue = base._enumDefaultValue;
_caseInsensitive = caseInsensitive;
}
/**
* @deprecated Since 2.9
*/
@Deprecated
public EnumDeserializer(EnumResolver byNameResolver) {
this(byNameResolver, null);
}
/**
* @deprecated Since 2.8
*/
@Deprecated
public static JsonDeserializer<?> deserializerForCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory) {
return deserializerForCreator(config, enumClass, factory, null, null);
}
/**
* Factory method used when Enum instances are to be deserialized
* using a creator (static factory method)
*
* @return Deserializer based on given factory method
*
* @since 2.8
*/
public static JsonDeserializer<?> deserializerForCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory,
ValueInstantiator valueInstantiator, SettableBeanProperty[] creatorProps)
{
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(factory.getMember(),
config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return new FactoryBasedEnumDeserializer(enumClass, factory,
factory.getParameterType(0),
valueInstantiator, creatorProps);
}
/**
* Factory method used when Enum instances are to be deserialized
* using a zero-/no-args factory method
*
* @return Deserializer based on given no-args factory method
*
* @since 2.8
*/
public static JsonDeserializer<?> deserializerForNoArgsCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory)
{
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(factory.getMember(),
config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return new FactoryBasedEnumDeserializer(enumClass, factory);
}
/**
* @since 2.9
*/
public EnumDeserializer withResolved(Boolean caseInsensitive) {
if (_caseInsensitive == caseInsensitive) {
return this;
}
return new EnumDeserializer(this, caseInsensitive);
}
@Override // since 2.9
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
Boolean caseInsensitive = findFormatFeature(ctxt, property, handledType(),
JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
if (caseInsensitive == null) {
caseInsensitive = _caseInsensitive;
}
return withResolved(caseInsensitive);
}
/*
/**********************************************************
/* Default JsonDeserializer implementation
/**********************************************************
*/
/**
* Because of costs associated with constructing Enum resolvers,
* let's cache instances by default.
*/
@Override
public boolean isCachable() { return true; }
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
JsonToken curr = p.currentToken();
// Usually should just get string value:
// 04-Sep-2020, tatu: for 2.11.3 / 2.12.0, removed "FIELD_NAME" as allowed;
// did not work and gave odd error message.
if (curr == JsonToken.VALUE_STRING) {
CompactStringObjectMap lookup = ctxt.isEnabled(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
? _getToStringLookup(ctxt) : _lookupByName;
final String name = p.getText();
Object result = lookup.find(name);
if (result == null) {
return _deserializeAltString(p, ctxt, lookup, name);
}
return result;
}
// But let's consider int acceptable as well (if within ordinal range)
if (curr == JsonToken.VALUE_NUMBER_INT) {
// ... unless told not to do that
int index = p.getIntValue();
if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) {
return ctxt.handleWeirdNumberValue(_enumClass(), index,
"not allowed to deserialize Enum value out of number: disable DeserializationConfig.DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS to allow"
);
}
if (index >= 0 && index < _enumsByIndex.length) {
return _enumsByIndex[index];
}
if ((_enumDefaultValue != null)
&& ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)) {
return _enumDefaultValue;
}
if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
return ctxt.handleWeirdNumberValue(_enumClass(), index,
"index value outside legal index range [0..%s]",
_enumsByIndex.length-1);
}
return null;
}
return _deserializeOther(p, ctxt);
}
/*
/**********************************************************
/* Internal helper methods
/**********************************************************
*/
private final Object _deserializeAltString(JsonParser p, DeserializationContext ctxt,
CompactStringObjectMap lookup, String name) throws IOException
{
name = name.trim();
if (name.length() == 0) {
if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
return getEmptyValue(ctxt);
}
} else {
// [databind#1313]: Case insensitive enum deserialization
if (Boolean.TRUE.equals(_caseInsensitive)) {
Object match = lookup.findCaseInsensitive(name);
if (match != null) {
return match;
}
} else if (!ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) {
// [databind#149]: Allow use of 'String' indexes as well -- unless prohibited (as per above)
char c = name.charAt(0);
if (c >= '0' && c <= '9') {
try {
int index = Integer.parseInt(name);
if (!ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS)) {
return ctxt.handleWeirdStringValue(_enumClass(), name,
"value looks like quoted Enum index, but `MapperFeature.ALLOW_COERCION_OF_SCALARS` prevents use"
);
}
if (index >= 0 && index < _enumsByIndex.length) {
return _enumsByIndex[index];
}
} catch (NumberFormatException e) {
// fine, ignore, was not an integer
}
}
}
}
if ((_enumDefaultValue != null)
&& ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)) {
return _enumDefaultValue;
}
if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
return ctxt.handleWeirdStringValue(_enumClass(), name,
"not one of the values accepted for Enum class: %s", lookup.keys());
}
return null;
}
protected Object _deserializeOther(JsonParser p, DeserializationContext ctxt) throws IOException
{
// [databind#381]
if (p.hasToken(JsonToken.START_ARRAY)) {
return _deserializeFromArray(p, ctxt);
}
return ctxt.handleUnexpectedToken(_enumClass(), p);
}
protected Class<?> _enumClass() {
return handledType();
}
protected CompactStringObjectMap _getToStringLookup(DeserializationContext ctxt)
{
CompactStringObjectMap lookup = _lookupByToString;
// note: exact locking not needed; all we care for here is to try to
// reduce contention for the initial resolution
if (lookup == null) {
synchronized (this) {
lookup = EnumResolver.constructUnsafeUsingToString(_enumClass(),
ctxt.getAnnotationIntrospector())
.constructLookup();
}
_lookupByToString = lookup;
}
return lookup;
}
}
| src/main/java/com/fasterxml/jackson/databind/deser/std/EnumDeserializer.java | package com.fasterxml.jackson.databind.deser.std;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.CompactStringObjectMap;
import com.fasterxml.jackson.databind.util.EnumResolver;
/**
* Deserializer class that can deserialize instances of
* specified Enum class from Strings and Integers.
*/
@JacksonStdImpl // was missing until 2.6
public class EnumDeserializer
extends StdScalarDeserializer<Object>
implements ContextualDeserializer
{
private static final long serialVersionUID = 1L;
protected Object[] _enumsByIndex;
/**
* @since 2.8
*/
private final Enum<?> _enumDefaultValue;
/**
* @since 2.7.3
*/
protected final CompactStringObjectMap _lookupByName;
/**
* Alternatively, we may need a different lookup object if "use toString"
* is defined.
*
* @since 2.7.3
*/
protected CompactStringObjectMap _lookupByToString;
protected final Boolean _caseInsensitive;
/**
* @since 2.9
*/
public EnumDeserializer(EnumResolver byNameResolver, Boolean caseInsensitive)
{
super(byNameResolver.getEnumClass());
_lookupByName = byNameResolver.constructLookup();
_enumsByIndex = byNameResolver.getRawEnums();
_enumDefaultValue = byNameResolver.getDefaultValue();
_caseInsensitive = caseInsensitive;
}
/**
* @since 2.9
*/
protected EnumDeserializer(EnumDeserializer base, Boolean caseInsensitive)
{
super(base);
_lookupByName = base._lookupByName;
_enumsByIndex = base._enumsByIndex;
_enumDefaultValue = base._enumDefaultValue;
_caseInsensitive = caseInsensitive;
}
/**
* @deprecated Since 2.9
*/
@Deprecated
public EnumDeserializer(EnumResolver byNameResolver) {
this(byNameResolver, null);
}
/**
* @deprecated Since 2.8
*/
@Deprecated
public static JsonDeserializer<?> deserializerForCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory) {
return deserializerForCreator(config, enumClass, factory, null, null);
}
/**
* Factory method used when Enum instances are to be deserialized
* using a creator (static factory method)
*
* @return Deserializer based on given factory method
*
* @since 2.8
*/
public static JsonDeserializer<?> deserializerForCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory,
ValueInstantiator valueInstantiator, SettableBeanProperty[] creatorProps)
{
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(factory.getMember(),
config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return new FactoryBasedEnumDeserializer(enumClass, factory,
factory.getParameterType(0),
valueInstantiator, creatorProps);
}
/**
* Factory method used when Enum instances are to be deserialized
* using a zero-/no-args factory method
*
* @return Deserializer based on given no-args factory method
*
* @since 2.8
*/
public static JsonDeserializer<?> deserializerForNoArgsCreator(DeserializationConfig config,
Class<?> enumClass, AnnotatedMethod factory)
{
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(factory.getMember(),
config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return new FactoryBasedEnumDeserializer(enumClass, factory);
}
/**
* @since 2.9
*/
public EnumDeserializer withResolved(Boolean caseInsensitive) {
if (_caseInsensitive == caseInsensitive) {
return this;
}
return new EnumDeserializer(this, caseInsensitive);
}
@Override // since 2.9
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
Boolean caseInsensitive = findFormatFeature(ctxt, property, handledType(),
JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
if (caseInsensitive == null) {
caseInsensitive = _caseInsensitive;
}
return withResolved(caseInsensitive);
}
/*
/**********************************************************
/* Default JsonDeserializer implementation
/**********************************************************
*/
/**
* Because of costs associated with constructing Enum resolvers,
* let's cache instances by default.
*/
@Override
public boolean isCachable() { return true; }
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
JsonToken curr = p.currentToken();
// Usually should just get string value:
if (curr == JsonToken.VALUE_STRING || curr == JsonToken.FIELD_NAME) {
CompactStringObjectMap lookup = ctxt.isEnabled(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
? _getToStringLookup(ctxt) : _lookupByName;
final String name = p.getText();
Object result = lookup.find(name);
if (result == null) {
return _deserializeAltString(p, ctxt, lookup, name);
}
return result;
}
// But let's consider int acceptable as well (if within ordinal range)
if (curr == JsonToken.VALUE_NUMBER_INT) {
// ... unless told not to do that
int index = p.getIntValue();
if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) {
return ctxt.handleWeirdNumberValue(_enumClass(), index,
"not allowed to deserialize Enum value out of number: disable DeserializationConfig.DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS to allow"
);
}
if (index >= 0 && index < _enumsByIndex.length) {
return _enumsByIndex[index];
}
if ((_enumDefaultValue != null)
&& ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)) {
return _enumDefaultValue;
}
if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
return ctxt.handleWeirdNumberValue(_enumClass(), index,
"index value outside legal index range [0..%s]",
_enumsByIndex.length-1);
}
return null;
}
return _deserializeOther(p, ctxt);
}
/*
/**********************************************************
/* Internal helper methods
/**********************************************************
*/
private final Object _deserializeAltString(JsonParser p, DeserializationContext ctxt,
CompactStringObjectMap lookup, String name) throws IOException
{
name = name.trim();
if (name.length() == 0) {
if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
return getEmptyValue(ctxt);
}
} else {
// [databind#1313]: Case insensitive enum deserialization
if (Boolean.TRUE.equals(_caseInsensitive)) {
Object match = lookup.findCaseInsensitive(name);
if (match != null) {
return match;
}
} else if (!ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) {
// [databind#149]: Allow use of 'String' indexes as well -- unless prohibited (as per above)
char c = name.charAt(0);
if (c >= '0' && c <= '9') {
try {
int index = Integer.parseInt(name);
if (!ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS)) {
return ctxt.handleWeirdStringValue(_enumClass(), name,
"value looks like quoted Enum index, but `MapperFeature.ALLOW_COERCION_OF_SCALARS` prevents use"
);
}
if (index >= 0 && index < _enumsByIndex.length) {
return _enumsByIndex[index];
}
} catch (NumberFormatException e) {
// fine, ignore, was not an integer
}
}
}
}
if ((_enumDefaultValue != null)
&& ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)) {
return _enumDefaultValue;
}
if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
return ctxt.handleWeirdStringValue(_enumClass(), name,
"not one of the values accepted for Enum class: %s", lookup.keys());
}
return null;
}
protected Object _deserializeOther(JsonParser p, DeserializationContext ctxt) throws IOException
{
// [databind#381]
if (p.hasToken(JsonToken.START_ARRAY)) {
return _deserializeFromArray(p, ctxt);
}
return ctxt.handleUnexpectedToken(_enumClass(), p);
}
protected Class<?> _enumClass() {
return handledType();
}
protected CompactStringObjectMap _getToStringLookup(DeserializationContext ctxt)
{
CompactStringObjectMap lookup = _lookupByToString;
// note: exact locking not needed; all we care for here is to try to
// reduce contention for the initial resolution
if (lookup == null) {
synchronized (this) {
lookup = EnumResolver.constructUnsafeUsingToString(_enumClass(),
ctxt.getAnnotationIntrospector())
.constructLookup();
}
_lookupByToString = lookup;
}
return lookup;
}
}
| Minor improvement to handling wrt #2823, less confusing exception message
| src/main/java/com/fasterxml/jackson/databind/deser/std/EnumDeserializer.java | Minor improvement to handling wrt #2823, less confusing exception message | <ide><path>rc/main/java/com/fasterxml/jackson/databind/deser/std/EnumDeserializer.java
<ide> JsonToken curr = p.currentToken();
<ide>
<ide> // Usually should just get string value:
<del> if (curr == JsonToken.VALUE_STRING || curr == JsonToken.FIELD_NAME) {
<add> // 04-Sep-2020, tatu: for 2.11.3 / 2.12.0, removed "FIELD_NAME" as allowed;
<add> // did not work and gave odd error message.
<add> if (curr == JsonToken.VALUE_STRING) {
<ide> CompactStringObjectMap lookup = ctxt.isEnabled(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
<ide> ? _getToStringLookup(ctxt) : _lookupByName;
<ide> final String name = p.getText(); |
|
Java | lgpl-2.1 | a0c8507763a6fb06fb50eb94c8d4690c1fc7bef6 | 0 | janissl/languagetool,jimregan/languagetool,janissl/languagetool,janissl/languagetool,janissl/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,lopescan/languagetool,meg0man/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,lopescan/languagetool,meg0man/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool,lopescan/languagetool,languagetool-org/languagetool,meg0man/languagetool,meg0man/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.fr;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.Category;
import org.languagetool.rules.RuleMatch;
import org.languagetool.tools.StringTools;
/**
* A rule that matches spaces before ?,:,; and ! (required for correct French
* punctuation).
*
* @see <a href="http://unicode.org/udhr/n/notes_fra.html">http://unicode.org/udhr/n/notes_fra.html</a>
*
* @author Marcin Miłkowski
*/
public class QuestionWhitespaceRule extends FrenchRule {
// Pattern used to avoid false positive when signaling missing
// space before and after colon ':' in URL with common schemes.
private static final Pattern urlPattern = Pattern.compile("^(file|s?ftp|finger|git|gopher|hdl|https?|shttp|imap|mailto|mms|nntp|s?news(post|reply)?|prospero|rsync|rtspu|sips?|svn|svn\\+ssh|telnet|wais)$");
public QuestionWhitespaceRule(final ResourceBundle messages) {
// super(messages);
super.setCategory(new Category(messages.getString("category_misc")));
}
@Override
public String getId() {
return "FRENCH_WHITESPACE";
}
@Override
public String getDescription() {
return "Insertion des espaces fines insécables";
}
@Override
public RuleMatch[] match(final AnalyzedSentence sentence) {
final List<RuleMatch> ruleMatches = new ArrayList<>();
final AnalyzedTokenReadings[] tokens = sentence.getTokens();
String prevToken = "";
for (int i = 1; i < tokens.length; i++) {
final String token = tokens[i].getToken();
final boolean isWhiteBefore = tokens[i].isWhitespaceBefore()
&& !"\u00A0".equals(prevToken) && !"\u202F".equals(prevToken);
String msg = null;
int fixLen = 0;
String suggestionText = null;
if (isWhiteBefore) {
switch (token) {
case "?":
msg = "Point d'interrogation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " ?";
fixLen = 1;
break;
case "!":
msg = "Point d'exclamation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " !";
fixLen = 1;
break;
case "»":
msg = "Le guillemet fermant est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " »";
fixLen = 1;
break;
case ";":
msg = "Point-virgule est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " ;";
fixLen = 1;
break;
case ":":
msg = "Deux-points sont précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " :";
fixLen = 1;
break;
}
} else {
// Strictly speaking, the character before ?!;: should be an
// "espace fine insécable" (U+202f). In practise, an
// "espace insécable" (U+00a0) is also often used. Let's accept both.
if (token.equals("?") && !prevToken.equals("!")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point d'interrogation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " ?";
fixLen = 1;
} else if (token.equals("!") && !prevToken.equals("?")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point d'exclamation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " !";
fixLen = 1;
} else if (token.equals(";")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point-virgule est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " ;";
fixLen = 1;
} else if (token.equals(":")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
// Avoid false positive for URL like http://www.languagetool.org.
final Matcher matcherUrl = urlPattern.matcher(prevToken);
if (!matcherUrl.find()) {
msg = "Deux-points précédés d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " :";
fixLen = 1;
}
} else if (token.equals("»")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Le guillemet fermant est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " »";
fixLen = 1;
}
}
if (StringTools.isEmpty(token) && prevToken.equals("«")) {
msg = "Le guillemet ouvrant est suivi d'une espace fine insécable.";
// non-breaking space
suggestionText = "« ";
fixLen = 1;
} else if (!StringTools.isEmpty(token) && prevToken.equals("«")
&& !token.equals("\u00a0") && !token.equals("\u202f")) {
msg = "Le guillemet ouvrant est suivi d'une espace fine insécable.";
// non-breaking space
suggestionText = "« ";
fixLen = 0;
}
if (msg != null) {
final int fromPos = tokens[i - 1].getStartPos();
final int toPos = tokens[i - 1].getStartPos() + fixLen
+ tokens[i - 1].getToken().length();
final RuleMatch ruleMatch = new RuleMatch(this, fromPos, toPos, msg,
"Insérer un espace insécable");
if (suggestionText != null) {
ruleMatch.setSuggestedReplacement(suggestionText);
}
ruleMatches.add(ruleMatch);
}
prevToken = token;
}
return toRuleMatchArray(ruleMatches);
}
@Override
public void reset() {
// nothing
}
}
| languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/QuestionWhitespaceRule.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.fr;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.Category;
import org.languagetool.rules.RuleMatch;
import org.languagetool.tools.StringTools;
/**
* A rule that matches spaces before ?,:,; and ! (required for correct French
* punctuation).
*
* @see <a href="http://unicode.org/udhr/n/notes_fra.html">http://unicode.org/udhr/n/notes_fra.html</a>
*
* @author Marcin Miłkowski
*/
public class QuestionWhitespaceRule extends FrenchRule {
// Pattern used to avoid false positive when signaling missing
// space before and after colon ':' in URL with common schemes.
private static final Pattern urlPattern = Pattern.compile("^(file|s?ftp|finger|git|gopher|hdl|https?|shttp|imap|mailto|mms|nntp|s?news(post|reply)?|prospero|rsync|rtspu|sips?|svn|svn\\+ssh|telnet|wais)$");
public QuestionWhitespaceRule(final ResourceBundle messages) {
// super(messages);
super.setCategory(new Category(messages.getString("category_misc")));
}
@Override
public String getId() {
return "FRENCH_WHITESPACE";
}
@Override
public String getDescription() {
return "Insertion des espaces fines insécables";
}
@Override
public RuleMatch[] match(final AnalyzedSentence sentence) {
final List<RuleMatch> ruleMatches = new ArrayList<>();
final AnalyzedTokenReadings[] tokens = sentence.getTokens();
String prevToken = "";
for (int i = 1; i < tokens.length; i++) {
final String token = tokens[i].getToken();
final boolean isWhiteBefore = tokens[i].isWhitespaceBefore() && !"\u00A0".equals(prevToken);
String msg = null;
int fixLen = 0;
String suggestionText = null;
if (isWhiteBefore) {
switch (token) {
case "?":
msg = "Point d'interrogation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " ?";
fixLen = 1;
break;
case "!":
msg = "Point d'exclamation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " !";
fixLen = 1;
break;
case "»":
msg = "Le guillemet fermant est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " »";
fixLen = 1;
break;
case ";":
msg = "Point-virgule est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " ;";
fixLen = 1;
break;
case ":":
msg = "Deux-points sont précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = " :";
fixLen = 1;
break;
}
} else {
// Strictly speaking, the character before ?!;: should be an
// "espace fine insécable" (U+202f). In practise, an
// "espace insécable" (U+00a0) is also often used. Let's accept both.
if (token.equals("?") && !prevToken.equals("!")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point d'interrogation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " ?";
fixLen = 1;
} else if (token.equals("!") && !prevToken.equals("?")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point d'exclamation est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " !";
fixLen = 1;
} else if (token.equals(";")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Point-virgule est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " ;";
fixLen = 1;
} else if (token.equals(":")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
// Avoid false positive for URL like http://www.languagetool.org.
final Matcher matcherUrl = urlPattern.matcher(prevToken);
if (!matcherUrl.find()) {
msg = "Deux-points précédés d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " :";
fixLen = 1;
}
} else if (token.equals("»")
&& !prevToken.equals("\u00a0") && !prevToken.equals("\u202f")) {
msg = "Le guillemet fermant est précédé d'une espace fine insécable.";
// non-breaking space
suggestionText = prevToken + " »";
fixLen = 1;
}
}
if (StringTools.isEmpty(token) && prevToken.equals("«")) {
msg = "Le guillemet ouvrant est suivi d'une espace fine insécable.";
// non-breaking space
suggestionText = "« ";
fixLen = 1;
} else if (!StringTools.isEmpty(token) && prevToken.equals("«")
&& !token.equals("\u00a0") && !token.equals("\u202f")) {
msg = "Le guillemet ouvrant est suivi d'une espace fine insécable.";
// non-breaking space
suggestionText = "« ";
fixLen = 0;
}
if (msg != null) {
final int fromPos = tokens[i - 1].getStartPos();
final int toPos = tokens[i - 1].getStartPos() + fixLen
+ tokens[i - 1].getToken().length();
final RuleMatch ruleMatch = new RuleMatch(this, fromPos, toPos, msg,
"Insérer un espace insécable");
if (suggestionText != null) {
ruleMatch.setSuggestedReplacement(suggestionText);
}
ruleMatches.add(ruleMatch);
}
prevToken = token;
}
return toRuleMatchArray(ruleMatches);
}
@Override
public void reset() {
// nothing
}
}
| [fr] accept also "espace fine insécable" (U+202f)
| languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/QuestionWhitespaceRule.java | [fr] accept also "espace fine insécable" (U+202f) | <ide><path>anguagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/QuestionWhitespaceRule.java
<ide> String prevToken = "";
<ide> for (int i = 1; i < tokens.length; i++) {
<ide> final String token = tokens[i].getToken();
<del> final boolean isWhiteBefore = tokens[i].isWhitespaceBefore() && !"\u00A0".equals(prevToken);
<add> final boolean isWhiteBefore = tokens[i].isWhitespaceBefore()
<add> && !"\u00A0".equals(prevToken) && !"\u202F".equals(prevToken);
<ide> String msg = null;
<ide> int fixLen = 0;
<ide> String suggestionText = null; |
|
Java | apache-2.0 | b525fcf85d41d46d68d48dc374696995c5f883c7 | 0 | gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom | /*
* Copyright 2017 Crown Copyright
*
* 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 stroom.resources.query.v1;
import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.datasource.api.v1.DataSource;
import stroom.query.api.v1.DocRef;
import stroom.query.api.v1.QueryKey;
import stroom.query.api.v1.SearchRequest;
import stroom.query.api.v1.SearchResponse;
import stroom.resources.ResourcePaths;
import stroom.statistics.server.sql.StatisticsQueryService;
import stroom.util.json.JsonUtil;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path(ResourcePaths.SQL_STATISTICS + ResourcePaths.V1)
@Produces(MediaType.APPLICATION_JSON)
public class SqlStatisticsQueryResource implements QueryResource {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlStatisticsQueryResource.class);
private StatisticsQueryService statisticsQueryService;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.DATA_SOURCE_ENDPOINT)
@Timed
public DataSource getDataSource(final DocRef docRef) {
if (LOGGER.isDebugEnabled()) {
String json = JsonUtil.writeValueAsString(docRef);
LOGGER.debug("/dataSource called with docRef:\n{}", json);
}
return statisticsQueryService.getDataSource(docRef);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.SEARCH_ENDPOINT)
@Timed
public SearchResponse search(final SearchRequest request) {
if (LOGGER.isDebugEnabled()) {
String json = JsonUtil.writeValueAsString(request);
LOGGER.debug("/search called with searchRequest:\n{}", json);
}
SearchResponse response = statisticsQueryService.search(request);
return response;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.DESTROY_ENDPOINT)
@Timed
public Boolean destroy(final QueryKey queryKey) {
if (LOGGER.isDebugEnabled()) {
String json = JsonUtil.writeValueAsString(queryKey);
LOGGER.debug("/destroy called with queryKey:\n{}", json);
}
return statisticsQueryService.destroy(queryKey);
}
public void setStatisticsQueryService(final StatisticsQueryService statisticsQueryService) {
this.statisticsQueryService = statisticsQueryService;
}
public HealthCheck.Result getHealth() {
if (statisticsQueryService == null) {
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("Dependency error!");
String statisticsQueryServiceMessage = " 'statisticsQueryService' has not been set!";
errorMessageBuilder.append(statisticsQueryServiceMessage);
return HealthCheck.Result.unhealthy(errorMessageBuilder.toString());
} else {
return HealthCheck.Result.healthy();
}
}
} | stroom-app/src/main/java/stroom/resources/query/v1/SqlStatisticsQueryResource.java | /*
* Copyright 2017 Crown Copyright
*
* 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 stroom.resources.query.v1;
import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.datasource.api.v1.DataSource;
import stroom.query.api.v1.DocRef;
import stroom.query.api.v1.QueryKey;
import stroom.query.api.v1.SearchRequest;
import stroom.query.api.v1.SearchResponse;
import stroom.resources.ResourcePaths;
import stroom.statistics.server.sql.StatisticsQueryService;
import stroom.util.json.JsonUtil;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path(ResourcePaths.SQL_STATISTICS + ResourcePaths.V1)
@Produces(MediaType.APPLICATION_JSON)
public class SqlStatisticsQueryResource implements QueryResource {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlStatisticsQueryResource.class);
private StatisticsQueryService statisticsQueryService;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.DATA_SOURCE_ENDPOINT)
@Timed
public DataSource getDataSource(final DocRef docRef) {
return statisticsQueryService.getDataSource(docRef);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.SEARCH_ENDPOINT)
@Timed
public SearchResponse search(final SearchRequest request) {
if (LOGGER.isDebugEnabled()) {
String json = JsonUtil.writeValueAsString(request);
LOGGER.debug("/search called with searchRequest:\n{}", json);
}
SearchResponse response = statisticsQueryService.search(request);
return response;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(QueryResource.DESTROY_ENDPOINT)
@Timed
public Boolean destroy(final QueryKey queryKey) {
return statisticsQueryService.destroy(queryKey);
}
public void setStatisticsQueryService(final StatisticsQueryService statisticsQueryService) {
this.statisticsQueryService = statisticsQueryService;
}
public HealthCheck.Result getHealth() {
if (statisticsQueryService == null) {
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("Dependency error!");
String statisticsQueryServiceMessage = " 'statisticsQueryService' has not been set!";
errorMessageBuilder.append(statisticsQueryServiceMessage);
return HealthCheck.Result.unhealthy(errorMessageBuilder.toString());
} else {
return HealthCheck.Result.healthy();
}
}
} | Add more logging to SqlStatisticsQueryResource
| stroom-app/src/main/java/stroom/resources/query/v1/SqlStatisticsQueryResource.java | Add more logging to SqlStatisticsQueryResource | <ide><path>troom-app/src/main/java/stroom/resources/query/v1/SqlStatisticsQueryResource.java
<ide> @Path(QueryResource.DATA_SOURCE_ENDPOINT)
<ide> @Timed
<ide> public DataSource getDataSource(final DocRef docRef) {
<add>
<add> if (LOGGER.isDebugEnabled()) {
<add> String json = JsonUtil.writeValueAsString(docRef);
<add> LOGGER.debug("/dataSource called with docRef:\n{}", json);
<add> }
<ide> return statisticsQueryService.getDataSource(docRef);
<ide> }
<ide>
<ide> @Path(QueryResource.DESTROY_ENDPOINT)
<ide> @Timed
<ide> public Boolean destroy(final QueryKey queryKey) {
<add> if (LOGGER.isDebugEnabled()) {
<add> String json = JsonUtil.writeValueAsString(queryKey);
<add> LOGGER.debug("/destroy called with queryKey:\n{}", json);
<add> }
<ide> return statisticsQueryService.destroy(queryKey);
<ide> }
<ide> |
|
JavaScript | mit | 3f837967d7e5f4c380587524fd78aca6ca7a81d2 | 0 | siimple/siimple-icons,siimple/siimple-icons | let fs = require("fs");
let path = require("path");
process.nextTick(function () {
//Global configuration
let iconsFolder = "./svg/";
let iconsFile = "./icons.json";
let unicodeStart = 57344;
//Read the icons folder
return fs.readdir(iconsFolder, function (error, files) {
if (error) {
process.stderr.write("ERROR: " + error.message);
return process.exit(1);
}
let icons = [];
let iconUnicode = unicodeStart;
// For each file in the list
files.forEach(function (file) {
// Check if the file has svg extension
if (path.extname(file) === ".svg") {
let icon = {
"id": path.basename(file, ".svg"),
"path": path.join(iconsFolder, file),
"unicode": iconUnicode,
"added": "v0.0.1",
"updated": "v0.0.1"
};
icons.push(icon);
//Increment the unicode counter
iconUnicode = iconUnicode + 1;
}
});
//Convert the icons list to string
let content = JSON.stringify(icons, null, 4);
//Write to the JSON file
return fs.writeFile(iconsFile, content, "utf8", function (error) {
if (error) {
process.stderr.write("ERROR: " + error.message);
return process.exit(1);
}
return process.exit(0);
});
});
});
| scripts/init.js | let fs = require("fs");
let path = require("path");
//Global configuration
let iconsFolder = "./svg/";
let iconsFile = "./icons.json";
let unicodeStart = 57344;
//Read the icons folder
fs.readdir(iconsFolder, function (error, files) {
if (error) {
throw error;
}
let icons = [];
let iconUnicode = unicodeStart;
// For each file in the list
files.forEach(function (file) {
// Check if the file has svg extension
if (path.extname(file) === ".svg") {
let icon = {
"id": path.basename(file, ".svg"),
"path": path.join(iconsFolder, file),
"unicode": iconUnicode,
"since": "v0.0.1"
};
icons.push(icon);
//Increment the unicode counter
iconUnicode = iconUnicode + 1;
}
});
//Convert the icons list to string
let content = JSON.stringify(icons, null, 4);
//Write to the JSON file
return fs.writeFile(iconsFile, content, "utf8", function (error) {
if (error) {
throw error;
}
//Display finish message
console.log("Init finished");
});
});
| Minor changes
| scripts/init.js | Minor changes | <ide><path>cripts/init.js
<ide> let fs = require("fs");
<ide> let path = require("path");
<ide>
<del>//Global configuration
<del>let iconsFolder = "./svg/";
<del>let iconsFile = "./icons.json";
<del>let unicodeStart = 57344;
<del>
<del>//Read the icons folder
<del>fs.readdir(iconsFolder, function (error, files) {
<del> if (error) {
<del> throw error;
<del> }
<del> let icons = [];
<del> let iconUnicode = unicodeStart;
<del> // For each file in the list
<del> files.forEach(function (file) {
<del> // Check if the file has svg extension
<del> if (path.extname(file) === ".svg") {
<del> let icon = {
<del> "id": path.basename(file, ".svg"),
<del> "path": path.join(iconsFolder, file),
<del> "unicode": iconUnicode,
<del> "since": "v0.0.1"
<del> };
<del> icons.push(icon);
<del> //Increment the unicode counter
<del> iconUnicode = iconUnicode + 1;
<add>process.nextTick(function () {
<add> //Global configuration
<add> let iconsFolder = "./svg/";
<add> let iconsFile = "./icons.json";
<add> let unicodeStart = 57344;
<add> //Read the icons folder
<add> return fs.readdir(iconsFolder, function (error, files) {
<add> if (error) {
<add> process.stderr.write("ERROR: " + error.message);
<add> return process.exit(1);
<ide> }
<add> let icons = [];
<add> let iconUnicode = unicodeStart;
<add> // For each file in the list
<add> files.forEach(function (file) {
<add> // Check if the file has svg extension
<add> if (path.extname(file) === ".svg") {
<add> let icon = {
<add> "id": path.basename(file, ".svg"),
<add> "path": path.join(iconsFolder, file),
<add> "unicode": iconUnicode,
<add> "added": "v0.0.1",
<add> "updated": "v0.0.1"
<add> };
<add> icons.push(icon);
<add> //Increment the unicode counter
<add> iconUnicode = iconUnicode + 1;
<add> }
<add> });
<add> //Convert the icons list to string
<add> let content = JSON.stringify(icons, null, 4);
<add> //Write to the JSON file
<add> return fs.writeFile(iconsFile, content, "utf8", function (error) {
<add> if (error) {
<add> process.stderr.write("ERROR: " + error.message);
<add> return process.exit(1);
<add> }
<add> return process.exit(0);
<add> });
<ide> });
<del> //Convert the icons list to string
<del> let content = JSON.stringify(icons, null, 4);
<del> //Write to the JSON file
<del> return fs.writeFile(iconsFile, content, "utf8", function (error) {
<del> if (error) {
<del> throw error;
<del> }
<del> //Display finish message
<del> console.log("Init finished");
<del> });
<ide> });
<ide> |
|
Java | mit | 4363bc7929d2bb9c68bf6cb924c6b7958ca2bada | 0 | opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples | package sample.javafx.property;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
public class Main {
public static void main(String[] args) {
DoubleProperty a = new SimpleDoubleProperty(1.0);
DoubleProperty b = new SimpleDoubleProperty(2.0);
DoubleBinding sum = a.add(b);
System.out.println("sum=" + sum.get());
a.set(3.0);
System.out.println("sum=" + sum.get());
}
}
| java/javafx/src/main/java/sample/javafx/property/Main.java | package sample.javafx.property;
import javafx.beans.property.SimpleDoubleProperty;
public class Main {
public static void main(String[] args) {
SimpleDoubleProperty a = new SimpleDoubleProperty();
a.addListener(System.out::println);
a.set(1.0);
a.set(2.0);
}
}
| JavaFX Hello Binding
| java/javafx/src/main/java/sample/javafx/property/Main.java | JavaFX Hello Binding | <ide><path>ava/javafx/src/main/java/sample/javafx/property/Main.java
<ide> package sample.javafx.property;
<ide>
<add>import javafx.beans.binding.DoubleBinding;
<add>import javafx.beans.property.DoubleProperty;
<ide> import javafx.beans.property.SimpleDoubleProperty;
<ide>
<ide> public class Main {
<ide> public static void main(String[] args) {
<del> SimpleDoubleProperty a = new SimpleDoubleProperty();
<add> DoubleProperty a = new SimpleDoubleProperty(1.0);
<add> DoubleProperty b = new SimpleDoubleProperty(2.0);
<add>
<add> DoubleBinding sum = a.add(b);
<add>
<add> System.out.println("sum=" + sum.get());
<ide>
<del> a.addListener(System.out::println);
<del>
<del> a.set(1.0);
<del> a.set(2.0);
<add> a.set(3.0);
<add>
<add> System.out.println("sum=" + sum.get());
<ide> }
<ide> } |
|
Java | apache-2.0 | 6758af468337bd76391771fe6e121a5aa0c9fc15 | 0 | operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver | package com.opera.core.systems.scope.internal;
public class OperaFlags {
//compile flags
//enable checks, disabled in internal use to allow clicking on disabled elements, etc..
public static final boolean ENABLE_CHECKS = false;
}
| src/com/opera/core/systems/scope/internal/OperaFlags.java | package com.opera.core.systems.scope.internal;
public class OperaFlags {
//compile flags
//enable checks, disabled in internal use to allow clicking on disabled elements, etc..
public static final boolean ENABLE_CHECKS = false;
//enable active window to be of type dialog, not allowed in interactive test (not cross platform)
//true for spartan, false for watir/webdriver
public static final boolean ENABLE_DIALOGS = true;
}
| We no longer need the dialog flag | src/com/opera/core/systems/scope/internal/OperaFlags.java | We no longer need the dialog flag | <ide><path>rc/com/opera/core/systems/scope/internal/OperaFlags.java
<ide> //enable checks, disabled in internal use to allow clicking on disabled elements, etc..
<ide> public static final boolean ENABLE_CHECKS = false;
<ide>
<del> //enable active window to be of type dialog, not allowed in interactive test (not cross platform)
<del> //true for spartan, false for watir/webdriver
<del> public static final boolean ENABLE_DIALOGS = true;
<ide> } |
|
Java | bsd-3-clause | 0a36bcb0c7693943c890d8d79ca8d37eaa550741 | 0 | nachoorme/cartodb-java-client | src/test/java/com/cartodb/Secret.java | package com.cartodb;
public class Secret {
public static final String user = "gkudos";
public static final String password = "azsxdcfvgbhn";
public static final String CONSUMER_KEY = "1MZDTC5p067g09j39D0Cye4bpAMDl99wbQ25GUU4";
public static final String CONSUMER_SECRET = "ZurIAGiECgCfgfliG225vPXsLK0D6EUqbWqXz24o";
public static final String API_KEY = "a3bc3e2d97cc0b05942583e2f03cab27ad04c039";
public static final String EXISTING_TABLE_WITH_DATA = "test";
}
| Delete Secret.java | src/test/java/com/cartodb/Secret.java | Delete Secret.java | <ide><path>rc/test/java/com/cartodb/Secret.java
<del>package com.cartodb;
<del>
<del>
<del>public class Secret {
<del>
<del> public static final String user = "gkudos";
<del> public static final String password = "azsxdcfvgbhn";
<del> public static final String CONSUMER_KEY = "1MZDTC5p067g09j39D0Cye4bpAMDl99wbQ25GUU4";
<del> public static final String CONSUMER_SECRET = "ZurIAGiECgCfgfliG225vPXsLK0D6EUqbWqXz24o";
<del> public static final String API_KEY = "a3bc3e2d97cc0b05942583e2f03cab27ad04c039";
<del> public static final String EXISTING_TABLE_WITH_DATA = "test";
<del>
<del>} |
||
JavaScript | mit | a0469694001ac681d97ae483b93a7ea91982e12f | 0 | sstur/node-restify,BryanDonovan/node-restify,ferhatsb/node-restify,heiparta/node-restify,meleslilijing/node-restify,thisandagain/node-restify,kusor/node-restify,rafael-custodio/node-restify,noseglid/node-restify,gwicke/node-restify,davepacheco/node-restify,rborn/node-restify,type/node-restify,chaordic/node-restify,rogervaas/node-restify,uWhisp/node-restify,13W/node-restify,sean3z/node-restify,occasl/node-restify,hekike/node-restify,restify/plugins,benjie/node-restify,pbouzakis/node-restify,myroid/node-restify,rsolomo/node-restify,zhuangya/node-restify,msaffitz/node-restify,timkuijsten/node-restify,wprater/node-restify,AlbertoElias/node-restify,micahr/node-restify,eodgooch/node-restify,rprieto/node-restify,trentm/node-restify,OiNutter/node-restify,anroOfCode/node-restify,spmason/node-restify,restify/node-restify,redmobile/node-restify,jokesterfr/node-restify,minmb/node-restify,mcavage/node-restify,w1nk/node-restify,othiym23/node-restify,jedahan/node-restify,liurq/node-restify,daankuijsten/node-restify,wilhelmmatilainen/node-restify,johnstonskj/node-restify,rgulewich/node-restify,aronwoost/node-restify,ernestopino/node-restify,sahat/node-restify,mgesmundo/logged-errors,gcochard/node-restify,skynet/node-restify,gergelyke/node-restify,AnyPresence/node-restify,andyburke/node-restify,mauricionr/node-restify,alfonsoc/node-restify,oroce/node-restify,lht/node-restify,thomaspeklak/node-restify,silverbucket/node-restify,restify/node-restify,myroid/node-restify,joyent/node-restify,jmealo/node-restify,VaclavObornik/node-restify,jameswomack/node-restify,timoxley/node-restify,eetuuuu/node-restify,alex-zhang/node-restify,cjpark87/node-restify,adunkman/node-restify,brycebaril/node-restify,tempbottle/node-restify,hmarr/node-restify,Nathanaela/node-restify,AsaAyers/node-restify,TheDeveloper/node-restify,MeetMe/node-restify,ojengwa/node-restify,ekristen/node-restify,dtorres/node-restify,iwarren/node-restify,Antariano/node-restify,twistedstream/node-restify,drewwells/node-restify,mboudreau/node-restify,rvagg/node-restify,rstuven/node-restify,tapquo/node-restify,jclulow/node-restify,prasmussen/node-restify,cat2608/node-restify,Echo3ToEcho7/node-restify,bendoerr/node-restify,djensen47/node-restify,datalanche/node-restify,KenanSulayman/node-restify,kevinykchan/node-restify | // Copyright 2011 Mark Cavage <[email protected]> All rights reserved.
var assert = require('assert');
var crypto = require('crypto');
var http = require('http');
var https = require('https');
var path = require('path');
var querystring = require('querystring');
var url = require('url');
var formidable = require('formidable');
var semver = require('semver');
var uuid = require('node-uuid');
var HttpCodes = require('./http_codes');
var RestCodes = require('./rest_codes');
var log = require('./log');
var newError = require('./error').newError;
// Just force this to extend http.ServerResponse
require('./http_extra');
///--- Internal Helpers
/**
* Cleans up sloppy URL paths, like /foo////bar/// to /foo/bar.
*
* @param {String} path the HTTP resource path.
* @return {String} Cleaned up form of path.
*/
function _sanitizePath(path) {
assert.ok(path);
if (log.trace())
log.trace('_sanitizePath: path=%s', path);
// Be nice like apache and strip out any //my//foo//bar///blah
var _path = path.replace(/\/\/+/g, '/');
// Kill a trailing '/'
if (_path.lastIndexOf('/') === (_path.length - 1) &&
_path.length > 1) {
_path = _path.substr(0, _path.length - 1);
}
if (log.trace())
log.trace('_sanitizePath: returning %s', _path);
return _path;
}
/**
* Checks if a mount matches, and if so, returns an object with all
* the :param variables.
*
* @param {String} path (request.url.pathname).
* @param {Object} route (what was mounted).
*/
function _matches(path, route) {
assert.ok(path);
assert.ok(route);
if (route.regex)
return route.url.exec(path);
if (path === route.url)
return {}; // there were no params if it was an exact match
var params = route.urlComponents;
var components = path.split('/').splice(1);
var len = components.length;
if (components.length !== params.length)
return null;
var parsed = {};
for (var i = 0; i < params.length; i++) {
// Don't use URL.parse, as it doesn't handle strings
// with ':' in them for this case. Regardless of what the
// RFC says about this, people do it.
var frag = components[i];
if (frag.indexOf('?') !== -1)
frag = frag.split('?', 2)[0];
if (params[i] === frag)
continue;
if (params[i].charAt(0) === ':') {
parsed[params[i].substr(1)] = frag;
continue;
}
return null;
}
return parsed;
}
function _parseAccept(request, response) {
assert.ok(request);
assert.ok(response);
assert.ok(request._config.acceptable);
assert.ok(request._config.acceptable.length);
if (!request.headers.accept) {
log.trace('_parseAccept: no accept header sent, using `default`');
response._accept = request.headers.accept = request._config.acceptable[0];
return true;
}
var mediaRanges = request.headers.accept.split(',');
for (var i = 0; i < mediaRanges.length; i++) {
var _accept = new RegExp(mediaRanges[i].split(';')[0].replace(/\*/g, '.*'));
log.warn('testing: '+_accept.source);
log.warn(JSON.stringify(request._config.acceptable));
for (var j = 0; j < request._config.acceptable.length; j++) {
if (_accept.test(request._config.acceptable[j])) {
response._accept = request._config.acceptable[j];
log.trace('Parsed accept type as: %s', response._accept);
return true;
}
}
}
response.sendError(newError({
httpCode: HttpCodes.NotAcceptable,
restCode: RestCodes.InvalidArgument,
message: request.headers.accept + ' unsupported',
details: request._config.acceptable
}));
return false;
}
function _parseAuthorization(req, res) {
req.authorization = {};
req.username = 'anonymous';
if (!req.headers.authorization) {
log.trace('No authorization header present.');
return true;
}
var pieces = req.headers.authorization.split(' ', 2);
if (!pieces || pieces.length !== 2) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'BasicAuth content is invalid.'
}));
return false;
}
req.authorization = {
scheme: pieces[0],
credentials: pieces[1]
};
if (pieces[0] === 'Basic') {
var decoded = (new Buffer(pieces[1], 'base64')).toString('utf8');
if (!decoded) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Authorization: Basic content is invalid (not base64).'
}));
return false;
}
pieces = decoded !== null ? decoded.split(':', 2) : null;
if (!(pieces !== null ? pieces[0] : null) ||
!(pieces !== null ? pieces[1] : null)) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Authorization: Basic content is invalid.'
}));
return false;
}
req.authorization.basic = {
username: pieces[0],
password: pieces[1]
};
req.username = pieces[0];
} else {
log.debug('Unknown authorization scheme %s. Skipping processing',
req.authorization.scheme);
}
return true;
}
function _parseDate(request, response) {
if (request.headers.date) {
try {
var date = new Date(request.headers.date);
var now = new Date();
if (log.trace())
log.trace('Date: sent=%d, now=%d, allowed=%d',
date.getTime(), now.getTime(), request._config.clockSkew);
if ((now.getTime() - date.getTime()) > request._config.clockSkew) {
response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Date header is too old'
}));
return false;
}
} catch (e) {
if (log.trace())
log.trace('Bad Date header: ' + e);
response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Date header is invalid'
}));
return false;
}
}
return true;
}
function _parseContentType(request, response) {
return request.contentType();
}
function _parseApiVersion(request, response) {
if (request.headers['x-api-version'])
request._version = request.headers['x-api-version'];
return true;
}
function _parseQueryString(request, response) {
request._url = url.parse(request.url);
if (request._url.query) {
var _qs = querystring.parse(request._url.query);
for (var k in _qs) {
if (_qs.hasOwnProperty(k)) {
assert.ok(!request.params[k]);
request.params[k] = _qs[k];
}
}
}
return true;
}
function _parseHead(request, response) {
assert.ok(request);
assert.ok(response);
log.trace('_parseHead:\n%s %s HTTP/%s\nHeaders: %o',
request.method,
request.url,
request.httpVersion,
request.headers);
if (!_parseAccept(request, response)) return false;
if (!_parseAuthorization(request, response)) return false;
if (!_parseDate(request, response)) return false;
if (!_parseApiVersion(request, response)) return false;
if (!_parseQueryString(request, response)) return false;
if (!_parseContentType(request, response)) return false;
return true;
}
function _parseRequest(request, response, next) {
assert.ok(request);
assert.ok(response);
assert.ok(next);
var contentType = request.contentType();
if (contentType === 'multipart/form-data') {
var form = formidable.IncomingForm();
form.maxFieldsSize = request._config.maxRequestSize;
form.on('error', function(err) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.BadRequest,
message: err.toString()
}));
});
form.on('field', function(field, value) {
log.trace('_parseRequest(multipart) field=%s, value=%s', field, value);
request.params[field] = value;
});
form.on('end', function() {
log.trace('_parseRequset(multipart): req.params=%o', request.params);
return next();
});
form.parse(request);
} else {
request.body = '';
request.on('data', function(chunk) {
request.body += chunk;
if (request.body.length > request._config.maxRequestSize) {
return response.sendError(newError({
httpCode: HttpCodes.RequestTooLarge,
restCode: RestCodes.RequestTooLarge,
message: 'maximum HTTP data size is 8k'
}));
}
});
request.on('end', function() {
if (request.body) {
log.trace('_parseRequest: req.body=%s', request.body);
var contentLen = request.headers['content-length'];
if (contentLen !== undefined) {
var actualLen = Buffer.byteLength(request.body, 'utf8');
if (parseInt(contentLen, 10) !== actualLen) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Content-Length=' + contentLen +
' didn\'t match actual length=' + actualLen
}));
}
}
var bParams;
try {
if (request._config.contentHandlers[contentType]) {
bParams = request._config.contentHandlers[contentType](request.body, request, response);
} else if (contentType) {
return response.sendError(newError({
httpCode: HttpCodes.UnsupportedMediaType,
restCode: RestCodes.InvalidArgument,
message: contentType + ' unsupported'
}));
}
} catch (e) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Invalid Content: ' + e.message
}));
}
for (var k in bParams) {
if (bParams.hasOwnProperty(k)) {
if (request.params.hasOwnProperty(k)) {
return response.sendError(newError({
httpCode: HttpCodes.Conflict,
restCode: RestCodes.InvalidArgument,
message: 'duplicate parameter detected: ' + k
}));
}
request.params[k] = bParams[k];
}
}
}
log.trace('_parseRequest: params parsed as: %o', request.params);
return next();
});
}
}
function _handleNoRoute(server, request, response) {
assert.ok(server);
assert.ok(request);
assert.ok(response);
var code = HttpCodes.NotFound;
var headers = {};
// This is such a one-off that it's saner to just handle it as such
if (request.method === 'OPTIONS' &&
request.url === '*') {
code = HttpCodes.Ok;
} else {
var urls = server.routes.urls;
for (var u in urls) {
if (urls.hasOwnProperty(u)) {
var route = urls[u];
var methods = [];
var versions = [];
var matched = false;
for (var i = 0; i < route.length; i++) {
if (methods.indexOf(route[i].method) === -1)
methods.push(route[i].method);
if (route[i].version && versions.indexOf(route[i].version) === -1)
versions.push(route[i].version);
if (_matches(request.url, route[i]))
matched = true;
}
if (matched) {
code = HttpCodes.BadMethod;
response._allowedMethods = methods;
if (versions.length) {
headers['x-api-versions'] = versions.join(', ');
if (methods.indexOf(request.method) !== -1)
code = HttpCodes.RetryWith;
}
if (request.method === 'OPTIONS') {
code = HttpCodes.Ok;
headers.Allow = methods.join(', ');
}
}
}
}
}
response.send(code, null, headers);
return log.w3cLog(request, response, function() {});
}
// --- Publicly available API
module.exports = {
/**
* Creates a new restify HTTP server.
*
* @param {Object} options a hash of configuration parameters:
* - serverName: String to send back in the Server header.
* Default: node.js.
* - maxRequestSize: Max request size to allow, in bytes.
* Default: 8192.
* - accept: Array of valid MIME types to allow in Accept.
* Default: application/json.
* - version: Default API version to support; setting this
* means clients are required to send an
* X-Api-Version header.
* Default: None.
* - clockSkew: If a Date header is present, allow N seconds
* of skew.
* Default: 300
* - logTo: a `Writable Stream` where log messages should go.
* Default: process.stderr.
* - contentHandlers: An object of
* 'type' -> function(body, req, res).
* or 'type' -> string where string is a built in
* content type, such as 'application/json'.
* Content types are overideable if you parse in
* a function instead of a string.
* Built in content types are:
* - application/json
* - application/x-www-form-urlencoded
* - application/jsonp
* Defaults to 'application/json'
* - contentWriters: An object of 'type' -> function(obj, req, res).
* or 'type' -> string where string is a built in
* content type, such as 'application/json'.
* The function should a return string from the
* passed in Object (obj). The same built in types
* as contentHandlers exist. Defaults to application/json
* - headers: An object of global headers that are sent back
* on all requests. Restify automatically sets:
* - X-Api-Version (if versioned)
* - X-Request-Id
* - X-Response-Time
* - Content-(Length|Type|MD5)
* - Access-Control-Allow-(Origin|Methods|Headers)
* - Access-Control-Expose-Headers
* If you don't set those particular keys, restify
* fills in default functions; if you do set them,
* you can fully override restify's defaults.
* Note that like contentWriters, this is an object
* with a string key as the header name, and the
* value is a function of the form f(response)
* which must return a string.
*
* @return {Object} node HTTP server, with restify "magic".
*/
createServer: function(options) {
var k;
var server;
function httpMain(request, response) {
assert.ok(request);
assert.ok(response);
var route;
var path = _sanitizePath(request.url);
request.url = path;
request.username = '';
request.requestId = response.requestId = uuid().toLowerCase();
request.startTime = response.startTime = new Date().getTime();
request._config = server._config;
request.params = {};
request.uriParams = {};
response.req = request;
response._method = request.method;
response._allowedMethods = ['OPTIONS'];
response._config = server._config;
response._sent = false;
response._errorSent = false;
// HTTP and HTTPS are different -> joyent/node GH #1005
var addr = request.connection.remoteAddress;
if (!addr) {
if (request.connection.socket) {
addr = request.connection.socket.remoteAddress;
} else {
addr = 'unknown';
}
}
request._remoteAddress = addr;
response._remoteAddress = addr;
if (!_parseHead(request, response))
return log.w3cLog(request, response, function() {});
if (!server.routes[request.method])
return _handleNoRoute(server, request, response);
var routes = server.routes[request.method];
for (var i = 0; i < routes.length; i++) {
var params = _matches(path, routes[i]);
if (params) {
// If the server isn't using versioning, just ignore
// whatever the client sent as a version header.
// If the server is, the client MUST send a version
// header. Unless the server is configured
// with weak versioning.
var ok = true;
if (routes[i].version && !server.weakVersions) {
if (request._version) {
if (routes[i].semver) {
ok = semver.satisfies(routes[i].version, request._version);
} else {
ok = (routes[i].version === request._version);
}
} else {
ok = false;
}
}
if (ok) {
request.uriParams = params;
route = routes[i];
if (route.version)
response._version = route.version;
for (var j = 0; j < server.routes.urls[route.url].length; j++) {
var r = server.routes.urls[route.url][j];
response._allowedMethods.push(r.method);
}
break;
}
}
}
if (!route)
return _handleNoRoute(server, request, response);
log.trace('%s %s route found -> %o', request.method, request.url, route);
var handler = 0;
var chain;
var stage = 0;
function runChain() {
return _parseRequest(request, response, function() {
var next = arguments.callee;
if (chain.length > 1) {
// Check if we need to skip to the post chain
if ((stage === 0 && response._sent) ||
(stage === 1 && response._errorSent)) {
stage = 2;
handler = 0;
}
}
if (!chain[stage])
return;
if (!chain[stage][handler]) {
if (++stage >= chain.length)
return;
handler = 0;
}
if (chain[stage][handler])
return chain[stage][handler++].call(this, request, response, next);
});
}
if (route.handlers.pre &&
route.handlers.main &&
route.handlers.post) {
chain = [
route.handlers.pre,
route.handlers.main,
route.handlers.post
];
} else {
chain = [route.handlers.main];
}
return runChain();
} // end httpMain
if (options && options.cert && options.key) {
server = https.createServer(options, httpMain);
} else {
server = http.createServer(httpMain);
}
server.logLevel = function(level) {
return log.level(level);
};
server.routes = {};
server._config = {};
server._config.contentHandlers = {};
server._config.contentWriters = {};
server._config.headers = {};
if (options) {
if (options.serverName)
server._config.serverName = options.serverName;
if (options.apiVersion && !options.version)
options.version = options.apiVersion;
if (options.version)
server._config.version = options.version;
if (options.maxRequestSize)
server._config.maxRequestSize = options.maxRequestSize;
if (options.acceptable)
server._config.acceptable = options.acceptable;
if (options.accept)
server._config.acceptable = options.accept;
if (options.clockSkew)
server._config.clockSkew = options.clockSkew * 1000;
if (options.logTo)
log.stderr(options.logTo);
if (options.fullErrors)
server._config.fullErrors = true;
if (options.sendErrorLogger)
server._config.sendErrorLogger = options.sendErrorLogger;
if (!options.contentHandlers)
options.contentHandlers = {'application/json' : 'application/json',
'application/x-www-form-urlencoded' : 'application/x-www-form-urlencoded'};
if (typeof(options.contentHandlers) !== 'object')
throw new TypeError('contentHandlers must be an object');
for (k in options.contentHandlers) {
if (options.contentHandlers.hasOwnProperty(k)) {
if (typeof(options.contentHandlers[k]) === 'function')
server._config.contentHandlers[k] = options.contentHandlers[k];
else if (typeof(options.contentHandlers[k]) === 'string') {
try {
var type = /^(.*)\(.*)$/i.exec(options.contentHandlers[k]); //type[1] will be <bar> from <foo>/<bar>
server._config.contentHandlers[k] = require('./contentTypes/'+type[1]).contentHandler();
} catch (e) {
throw new Error('could not import contentHandler '+options.contentHandlers[k]);
}
} else
throw new TypeError('contentWriters values must be functions or type strings');
}
}
if (!options.contentWriters) //set up defaults
options.contentWriters = {'application/json' : 'application/json',
'application/x-www-form-urlencoded' : 'application/x-www-form-urlencoded'};
if (typeof(options.contentWriters) !== 'object')
throw new TypeError('contentWriters must be an object');
for (k in options.contentWriters) {
if (options.contentWriters.hasOwnProperty(k)) {
if (typeof(options.contentWriters[k]) === 'function')
server._config.contentWriters[k] = options.contentWriters[k];
else if (typeof(options.contentWriters[k]) === 'string') {
try {
var type = /^(.*)\(.*)$/i.exec(options.contentWriters[k]); //type[1] will be <bar> from <foo>/<bar>
server._config.contentWriters[k] = require('./contentTypes/'+type[1]).contentWriter();
} catch (e) {
throw new Error('could not import contentWriter '+options.contentWriters[k]);
}
} else
throw new TypeError('contentWriters values must be functions or type strings');
}
}
if (options.headers) {
if (typeof(options.headers) !== 'object')
throw new TypeError('headers must be an object');
for (k in options.headers) {
if (options.headers.hasOwnProperty(k)) {
if (typeof(options.headers[k]) !== 'function')
throw new TypeError('headers values must be functions');
server._config.headers[k] = options.headers[k];
}
}
}
}
if (!server._config.serverName)
server._config.serverName = 'node.js';
if (!server._config.maxRequestSize)
server._config.maxRequestSize = 8192;
if (!server._config.clockSkew)
server._config.clockSkew = 300 * 1000; // Default 5m
if (!server.sendErrorLogLevel)
server._config.sendErrorLogger = log.warn;
if (!server._config.acceptable) {
server._config.acceptable = [
'application/json'
];
}
server._config._acceptable = {};
for (var i = 0; i < server._config.acceptable.length; i++) {
var tmp = server._config.acceptable[i].split('/');
if (!server._config._acceptable[tmp[0]]) {
server._config._acceptable[tmp[0]] = [tmp[1]];
} else {
var found = false;
for (var j = 0; j < server._config._acceptable[tmp[0]].length; j++) {
if (server._config._acceptable[tmp[0]][j] === tmp[1]) {
found = true;
break;
}
}
if (!found) {
server._config._acceptable[tmp[0]].push(tmp[1]);
}
}
}
log.trace('server will accept types: %o', server._config.acceptable);
var foundXApiVersion = false;
var foundXRequestId = false;
var foundXResponseTime = false;
var foundContentLength = false;
var foundContentType = false;
var foundContentMD5 = false;
var foundACAO = false;
var foundACAM = false;
var foundACAH = false;
var foundACEH = false;
for (k in server._config.headers) {
if (server._config.headers.hasOwnProperty(k)) {
var h = k.toLowerCase();
switch (h) {
case 'x-api-version':
foundXApiVersion = true;
break;
case 'x-request-id':
foundXRequestId = true;
break;
case 'x-response-time':
foundXResponseTime = true;
break;
case 'content-length':
foundContentLength = true;
break;
case 'content-type':
foundContentType = true;
break;
case 'content-md5':
foundContentMD5 = true;
break;
case 'access-control-allow-origin':
foundACAO = true;
break;
case 'access-control-allow-method':
foundACAM = true;
break;
case 'access-control-allow-headers':
foundACAH = true;
break;
case 'access-control-expose-headers':
foundACEH = true;
break;
}
}
}
if (!foundXApiVersion) {
server._config.headers['X-Api-Version'] = function(res) {
return res._version;
};
}
if (!foundXRequestId) {
server._config.headers['X-Request-Id'] = function(res) {
return res.requestId;
};
}
if (!foundXResponseTime) {
server._config.headers['X-Response-Time'] = function(res) {
return res._time;
};
}
if (!foundContentLength) {
server._config.headers['Content-Length'] = function(res) {
if (!res.options.noEnd && res._method !== 'HEAD' && res._data) {
res._bytes = Buffer.byteLength(res._data, 'utf8');
return res._bytes;
}
};
}
if (!foundContentMD5) {
server._config.headers['Content-MD5'] = function(res) {
if (res._data && res.options.code !== 204) {
if (!res.options.noContentMD5) {
var hash = crypto.createHash('md5');
hash.update(res._data);
return hash.digest('base64');
}
}
};
}
if (!foundContentType) {
server._config.headers['Content-Type'] = function(res) {
if (res._data && res.options.code !== 204)
return res._accept;
};
}
if (!foundACAO) {
server._config.headers['Access-Control-Allow-Origin'] = function(res) {
return '*';
};
}
if (!foundACAM) {
server._config.headers['Access-Control-Allow-Methods'] = function(res) {
if (res._allowedMethods && res._allowedMethods.length)
return res._allowedMethods.join(', ');
};
}
if (!foundACAH) {
server._config.headers['Access-Control-Allow-Headers'] = function(res) {
return [
'Accept',
'Content-Type',
'Content-Length',
'Date',
'X-Api-Version'
].join(', ');
};
}
if (!foundACEH) {
server._config.headers['Access-Control-Expose-Headers'] = function(res) {
return [
'X-Api-Version',
'X-Request-Id',
'X-Response-Time'
].join(', ');
};
}
return server;
}
};
| lib/server.js | // Copyright 2011 Mark Cavage <[email protected]> All rights reserved.
var assert = require('assert');
var crypto = require('crypto');
var http = require('http');
var https = require('https');
var path = require('path');
var querystring = require('querystring');
var url = require('url');
var formidable = require('formidable');
var semver = require('semver');
var uuid = require('node-uuid');
var HttpCodes = require('./http_codes');
var RestCodes = require('./rest_codes');
var log = require('./log');
var newError = require('./error').newError;
// Just force this to extend http.ServerResponse
require('./http_extra');
///--- Internal Helpers
/**
* Cleans up sloppy URL paths, like /foo////bar/// to /foo/bar.
*
* @param {String} path the HTTP resource path.
* @return {String} Cleaned up form of path.
*/
function _sanitizePath(path) {
assert.ok(path);
if (log.trace())
log.trace('_sanitizePath: path=%s', path);
// Be nice like apache and strip out any //my//foo//bar///blah
var _path = path.replace(/\/\/+/g, '/');
// Kill a trailing '/'
if (_path.lastIndexOf('/') === (_path.length - 1) &&
_path.length > 1) {
_path = _path.substr(0, _path.length - 1);
}
if (log.trace())
log.trace('_sanitizePath: returning %s', _path);
return _path;
}
/**
* Checks if a mount matches, and if so, returns an object with all
* the :param variables.
*
* @param {String} path (request.url.pathname).
* @param {Object} route (what was mounted).
*/
function _matches(path, route) {
assert.ok(path);
assert.ok(route);
if (route.regex)
return route.url.exec(path);
if (path === route.url)
return {}; // there were no params if it was an exact match
var params = route.urlComponents;
var components = path.split('/').splice(1);
var len = components.length;
if (components.length !== params.length)
return null;
var parsed = {};
for (var i = 0; i < params.length; i++) {
// Don't use URL.parse, as it doesn't handle strings
// with ':' in them for this case. Regardless of what the
// RFC says about this, people do it.
var frag = components[i];
if (frag.indexOf('?') !== -1)
frag = frag.split('?', 2)[0];
if (params[i] === frag)
continue;
if (params[i].charAt(0) === ':') {
parsed[params[i].substr(1)] = frag;
continue;
}
return null;
}
return parsed;
}
function _parseAccept(request, response) {
assert.ok(request);
assert.ok(response);
assert.ok(request._config.acceptable);
assert.ok(request._config.acceptable.length);
if (!request.headers.accept) {
log.trace('_parseAccept: no accept header sent, using `default`');
response._accept = request.headers.accept = request._config.acceptable[0];
return true;
}
var mediaRanges = request.headers.accept.split(',');
for (var i = 0; i < mediaRanges.length; i++) {
var _accept = new RegExp(mediaRanges[i].split(';')[0].replace(/\*/g, '.*'));
log.warn('testing: '+_accept.source);
log.warn(JSON.stringify(request._config.acceptable));
for (var j = 0; j < request._config.acceptable.length; j++) {
if (_accept.test(request._config.acceptable[j])) {
response._accept = request._config.acceptable[j];
log.trace('Parsed accept type as: %s', response._accept);
return true;
}
}
}
response.sendError(newError({
httpCode: HttpCodes.NotAcceptable,
restCode: RestCodes.InvalidArgument,
message: request.headers.accept + ' unsupported',
details: request._config.acceptable
}));
return false;
}
function _parseAuthorization(req, res) {
req.authorization = {};
req.username = 'anonymous';
if (!req.headers.authorization) {
log.trace('No authorization header present.');
return true;
}
var pieces = req.headers.authorization.split(' ', 2);
if (!pieces || pieces.length !== 2) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'BasicAuth content is invalid.'
}));
return false;
}
req.authorization = {
scheme: pieces[0],
credentials: pieces[1]
};
if (pieces[0] === 'Basic') {
var decoded = (new Buffer(pieces[1], 'base64')).toString('utf8');
if (!decoded) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Authorization: Basic content is invalid (not base64).'
}));
return false;
}
pieces = decoded !== null ? decoded.split(':', 2) : null;
if (!(pieces !== null ? pieces[0] : null) ||
!(pieces !== null ? pieces[1] : null)) {
res.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Authorization: Basic content is invalid.'
}));
return false;
}
req.authorization.basic = {
username: pieces[0],
password: pieces[1]
};
req.username = pieces[0];
} else {
log.debug('Unknown authorization scheme %s. Skipping processing',
req.authorization.scheme);
}
return true;
}
function _parseDate(request, response) {
if (request.headers.date) {
try {
var date = new Date(request.headers.date);
var now = new Date();
if (log.trace())
log.trace('Date: sent=%d, now=%d, allowed=%d',
date.getTime(), now.getTime(), request._config.clockSkew);
if ((now.getTime() - date.getTime()) > request._config.clockSkew) {
response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Date header is too old'
}));
return false;
}
} catch (e) {
if (log.trace())
log.trace('Bad Date header: ' + e);
response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Date header is invalid'
}));
return false;
}
}
return true;
}
function _parseContentType(request, response) {
return request.contentType();
}
function _parseApiVersion(request, response) {
if (request.headers['x-api-version'])
request._version = request.headers['x-api-version'];
return true;
}
function _parseQueryString(request, response) {
request._url = url.parse(request.url);
if (request._url.query) {
var _qs = querystring.parse(request._url.query);
for (var k in _qs) {
if (_qs.hasOwnProperty(k)) {
assert.ok(!request.params[k]);
request.params[k] = _qs[k];
}
}
}
return true;
}
function _parseHead(request, response) {
assert.ok(request);
assert.ok(response);
log.trace('_parseHead:\n%s %s HTTP/%s\nHeaders: %o',
request.method,
request.url,
request.httpVersion,
request.headers);
if (!_parseAccept(request, response)) return false;
if (!_parseAuthorization(request, response)) return false;
if (!_parseDate(request, response)) return false;
if (!_parseApiVersion(request, response)) return false;
if (!_parseQueryString(request, response)) return false;
if (!_parseContentType(request, response)) return false;
return true;
}
function _parseRequest(request, response, next) {
assert.ok(request);
assert.ok(response);
assert.ok(next);
var contentType = request.contentType();
if (contentType === 'multipart/form-data') {
var form = formidable.IncomingForm();
form.maxFieldsSize = request._config.maxRequestSize;
form.on('error', function(err) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.BadRequest,
message: err.toString()
}));
});
form.on('field', function(field, value) {
log.trace('_parseRequest(multipart) field=%s, value=%s', field, value);
request.params[field] = value;
});
form.on('end', function() {
log.trace('_parseRequset(multipart): req.params=%o', request.params);
return next();
});
form.parse(request);
} else {
request.body = '';
request.on('data', function(chunk) {
request.body += chunk;
if (request.body.length > request._config.maxRequestSize) {
return response.sendError(newError({
httpCode: HttpCodes.RequestTooLarge,
restCode: RestCodes.RequestTooLarge,
message: 'maximum HTTP data size is 8k'
}));
}
});
request.on('end', function() {
if (request.body) {
log.trace('_parseRequest: req.body=%s', request.body);
var contentLen = request.headers['content-length'];
if (contentLen !== undefined) {
var actualLen = Buffer.byteLength(request.body, 'utf8');
if (parseInt(contentLen, 10) !== actualLen) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidHeader,
message: 'Content-Length=' + contentLen +
' didn\'t match actual length=' + actualLen
}));
}
}
var bParams;
try {
if (contentType === 'application/x-www-form-urlencoded') {
bParams = querystring.parse(request.body) || {};
} else if (contentType === 'application/json') {
bParams = JSON.parse(request.body);
} else if (request._config.contentHandlers[contentType]) {
var fn = request._config.contentHandlers[contentType];
bParams = fn(request.body);
} else if (contentType) {
return response.sendError(newError({
httpCode: HttpCodes.UnsupportedMediaType,
restCode: RestCodes.InvalidArgument,
message: contentType + ' unsupported'
}));
}
} catch (e) {
return response.sendError(newError({
httpCode: HttpCodes.BadRequest,
restCode: RestCodes.InvalidArgument,
message: 'Invalid Content: ' + e.message
}));
}
for (var k in bParams) {
if (bParams.hasOwnProperty(k)) {
if (request.params.hasOwnProperty(k)) {
return response.sendError(newError({
httpCode: HttpCodes.Conflict,
restCode: RestCodes.InvalidArgument,
message: 'duplicate parameter detected: ' + k
}));
}
request.params[k] = bParams[k];
}
}
}
log.trace('_parseRequest: params parsed as: %o', request.params);
return next();
});
}
}
function _handleNoRoute(server, request, response) {
assert.ok(server);
assert.ok(request);
assert.ok(response);
var code = HttpCodes.NotFound;
var headers = {};
// This is such a one-off that it's saner to just handle it as such
if (request.method === 'OPTIONS' &&
request.url === '*') {
code = HttpCodes.Ok;
} else {
var urls = server.routes.urls;
for (var u in urls) {
if (urls.hasOwnProperty(u)) {
var route = urls[u];
var methods = [];
var versions = [];
var matched = false;
for (var i = 0; i < route.length; i++) {
if (methods.indexOf(route[i].method) === -1)
methods.push(route[i].method);
if (route[i].version && versions.indexOf(route[i].version) === -1)
versions.push(route[i].version);
if (_matches(request.url, route[i]))
matched = true;
}
if (matched) {
code = HttpCodes.BadMethod;
response._allowedMethods = methods;
if (versions.length) {
headers['x-api-versions'] = versions.join(', ');
if (methods.indexOf(request.method) !== -1)
code = HttpCodes.RetryWith;
}
if (request.method === 'OPTIONS') {
code = HttpCodes.Ok;
headers.Allow = methods.join(', ');
}
}
}
}
}
response.send(code, null, headers);
return log.w3cLog(request, response, function() {});
}
// --- Publicly available API
module.exports = {
/**
* Creates a new restify HTTP server.
*
* @param {Object} options a hash of configuration parameters:
* - serverName: String to send back in the Server header.
* Default: node.js.
* - maxRequestSize: Max request size to allow, in bytes.
* Default: 8192.
* - accept: Array of valid MIME types to allow in Accept.
* Default: application/json.
* - version: Default API version to support; setting this
* means clients are required to send an
* X-Api-Version header.
* Default: None.
* - clockSkew: If a Date header is present, allow N seconds
* of skew.
* Default: 300
* - logTo: a `Writable Stream` where log messages should go.
* Default: process.stderr.
* - contentHandlers: An object of
* 'type' -> function(body, req, res).
* or 'type' -> string where string is a built in
* content type, such as 'application/json'.
* Content types are overideable if you parse in
* a function instead of a string.
* Built in content types are:
* - application/json
* - application/x-www-form-urlencoded
* - application/jsonp
* Defaults to 'application/json'
* - contentWriters: An object of 'type' -> function(obj, req, res).
* or 'type' -> string where string is a built in
* content type, such as 'application/json'.
* The function should a return string from the
* passed in Object (obj). The same built in types
* as contentHandlers exist. Defaults to application/json
* - headers: An object of global headers that are sent back
* on all requests. Restify automatically sets:
* - X-Api-Version (if versioned)
* - X-Request-Id
* - X-Response-Time
* - Content-(Length|Type|MD5)
* - Access-Control-Allow-(Origin|Methods|Headers)
* - Access-Control-Expose-Headers
* If you don't set those particular keys, restify
* fills in default functions; if you do set them,
* you can fully override restify's defaults.
* Note that like contentWriters, this is an object
* with a string key as the header name, and the
* value is a function of the form f(response)
* which must return a string.
*
* @return {Object} node HTTP server, with restify "magic".
*/
createServer: function(options) {
var k;
var server;
function httpMain(request, response) {
assert.ok(request);
assert.ok(response);
var route;
var path = _sanitizePath(request.url);
request.url = path;
request.username = '';
request.requestId = response.requestId = uuid().toLowerCase();
request.startTime = response.startTime = new Date().getTime();
request._config = server._config;
request.params = {};
request.uriParams = {};
response.req = request;
response._method = request.method;
response._allowedMethods = ['OPTIONS'];
response._config = server._config;
response._sent = false;
response._errorSent = false;
// HTTP and HTTPS are different -> joyent/node GH #1005
var addr = request.connection.remoteAddress;
if (!addr) {
if (request.connection.socket) {
addr = request.connection.socket.remoteAddress;
} else {
addr = 'unknown';
}
}
request._remoteAddress = addr;
response._remoteAddress = addr;
if (!_parseHead(request, response))
return log.w3cLog(request, response, function() {});
if (!server.routes[request.method])
return _handleNoRoute(server, request, response);
var routes = server.routes[request.method];
for (var i = 0; i < routes.length; i++) {
var params = _matches(path, routes[i]);
if (params) {
// If the server isn't using versioning, just ignore
// whatever the client sent as a version header.
// If the server is, the client MUST send a version
// header. Unless the server is configured
// with weak versioning.
var ok = true;
if (routes[i].version && !server.weakVersions) {
if (request._version) {
if (routes[i].semver) {
ok = semver.satisfies(routes[i].version, request._version);
} else {
ok = (routes[i].version === request._version);
}
} else {
ok = false;
}
}
if (ok) {
request.uriParams = params;
route = routes[i];
if (route.version)
response._version = route.version;
for (var j = 0; j < server.routes.urls[route.url].length; j++) {
var r = server.routes.urls[route.url][j];
response._allowedMethods.push(r.method);
}
break;
}
}
}
if (!route)
return _handleNoRoute(server, request, response);
log.trace('%s %s route found -> %o', request.method, request.url, route);
var handler = 0;
var chain;
var stage = 0;
function runChain() {
return _parseRequest(request, response, function() {
var next = arguments.callee;
if (chain.length > 1) {
// Check if we need to skip to the post chain
if ((stage === 0 && response._sent) ||
(stage === 1 && response._errorSent)) {
stage = 2;
handler = 0;
}
}
if (!chain[stage])
return;
if (!chain[stage][handler]) {
if (++stage >= chain.length)
return;
handler = 0;
}
if (chain[stage][handler])
return chain[stage][handler++].call(this, request, response, next);
});
}
if (route.handlers.pre &&
route.handlers.main &&
route.handlers.post) {
chain = [
route.handlers.pre,
route.handlers.main,
route.handlers.post
];
} else {
chain = [route.handlers.main];
}
return runChain();
} // end httpMain
if (options && options.cert && options.key) {
server = https.createServer(options, httpMain);
} else {
server = http.createServer(httpMain);
}
server.logLevel = function(level) {
return log.level(level);
};
server.routes = {};
server._config = {};
server._config.contentHandlers = {};
server._config.contentWriters = {};
server._config.headers = {};
if (options) {
if (options.serverName)
server._config.serverName = options.serverName;
if (options.apiVersion && !options.version)
options.version = options.apiVersion;
if (options.version)
server._config.version = options.version;
if (options.maxRequestSize)
server._config.maxRequestSize = options.maxRequestSize;
if (options.acceptable)
server._config.acceptable = options.acceptable;
if (options.accept)
server._config.acceptable = options.accept;
if (options.clockSkew)
server._config.clockSkew = options.clockSkew * 1000;
if (options.logTo)
log.stderr(options.logTo);
if (options.fullErrors)
server._config.fullErrors = true;
if (options.sendErrorLogger)
server._config.sendErrorLogger = options.sendErrorLogger;
if (!options.contentHandlers)
options.contentHandlers = {'application/json' : 'application/json',
'application/x-www-form-urlencoded' : 'application/x-www-form-urlencoded'};
if (typeof(options.contentHandlers) !== 'object')
throw new TypeError('contentHandlers must be an object');
for (k in options.contentHandlers) {
if (options.contentHandlers.hasOwnProperty(k)) {
if (typeof(options.contentHandlers[k]) === 'function')
server._config.contentHandlers[k] = options.contentHandlers[k];
else if (typeof(options.contentHandlers[k]) === 'string') {
try {
var type = /^(.*)\(.*)$/i.exec(options.contentHandlers[k]); //type[1] will be <bar> from <foo>/<bar>
server._config.contentHandlers[k] = require('./contentTypes/'+type[1]).contentHandler();
} catch (e) {
throw new Error('could not import contentHandler '+options.contentHandlers[k]);
}
} else
throw new TypeError('contentWriters values must be functions or type strings');
}
}
if (!options.contentWriters) //set up defaults
options.contentWriters = {'application/json' : 'application/json',
'application/x-www-form-urlencoded' : 'application/x-www-form-urlencoded'};
if (typeof(options.contentWriters) !== 'object')
throw new TypeError('contentWriters must be an object');
for (k in options.contentWriters) {
if (options.contentWriters.hasOwnProperty(k)) {
if (typeof(options.contentWriters[k]) === 'function')
server._config.contentWriters[k] = options.contentWriters[k];
else if (typeof(options.contentWriters[k]) === 'string') {
try {
var type = /^(.*)\(.*)$/i.exec(options.contentWriters[k]); //type[1] will be <bar> from <foo>/<bar>
server._config.contentWriters[k] = require('./contentTypes/'+type[1]).contentWriter();
} catch (e) {
throw new Error('could not import contentWriter '+options.contentWriters[k]);
}
} else
throw new TypeError('contentWriters values must be functions or type strings');
}
}
if (options.headers) {
if (typeof(options.headers) !== 'object')
throw new TypeError('headers must be an object');
for (k in options.headers) {
if (options.headers.hasOwnProperty(k)) {
if (typeof(options.headers[k]) !== 'function')
throw new TypeError('headers values must be functions');
server._config.headers[k] = options.headers[k];
}
}
}
}
if (!server._config.serverName)
server._config.serverName = 'node.js';
if (!server._config.maxRequestSize)
server._config.maxRequestSize = 8192;
if (!server._config.clockSkew)
server._config.clockSkew = 300 * 1000; // Default 5m
if (!server.sendErrorLogLevel)
server._config.sendErrorLogger = log.warn;
if (!server._config.acceptable) {
server._config.acceptable = [
'application/json'
];
}
server._config._acceptable = {};
for (var i = 0; i < server._config.acceptable.length; i++) {
var tmp = server._config.acceptable[i].split('/');
if (!server._config._acceptable[tmp[0]]) {
server._config._acceptable[tmp[0]] = [tmp[1]];
} else {
var found = false;
for (var j = 0; j < server._config._acceptable[tmp[0]].length; j++) {
if (server._config._acceptable[tmp[0]][j] === tmp[1]) {
found = true;
break;
}
}
if (!found) {
server._config._acceptable[tmp[0]].push(tmp[1]);
}
}
}
log.trace('server will accept types: %o', server._config.acceptable);
var foundXApiVersion = false;
var foundXRequestId = false;
var foundXResponseTime = false;
var foundContentLength = false;
var foundContentType = false;
var foundContentMD5 = false;
var foundACAO = false;
var foundACAM = false;
var foundACAH = false;
var foundACEH = false;
for (k in server._config.headers) {
if (server._config.headers.hasOwnProperty(k)) {
var h = k.toLowerCase();
switch (h) {
case 'x-api-version':
foundXApiVersion = true;
break;
case 'x-request-id':
foundXRequestId = true;
break;
case 'x-response-time':
foundXResponseTime = true;
break;
case 'content-length':
foundContentLength = true;
break;
case 'content-type':
foundContentType = true;
break;
case 'content-md5':
foundContentMD5 = true;
break;
case 'access-control-allow-origin':
foundACAO = true;
break;
case 'access-control-allow-method':
foundACAM = true;
break;
case 'access-control-allow-headers':
foundACAH = true;
break;
case 'access-control-expose-headers':
foundACEH = true;
break;
}
}
}
if (!foundXApiVersion) {
server._config.headers['X-Api-Version'] = function(res) {
return res._version;
};
}
if (!foundXRequestId) {
server._config.headers['X-Request-Id'] = function(res) {
return res.requestId;
};
}
if (!foundXResponseTime) {
server._config.headers['X-Response-Time'] = function(res) {
return res._time;
};
}
if (!foundContentLength) {
server._config.headers['Content-Length'] = function(res) {
if (!res.options.noEnd && res._method !== 'HEAD' && res._data) {
res._bytes = Buffer.byteLength(res._data, 'utf8');
return res._bytes;
}
};
}
if (!foundContentMD5) {
server._config.headers['Content-MD5'] = function(res) {
if (res._data && res.options.code !== 204) {
if (!res.options.noContentMD5) {
var hash = crypto.createHash('md5');
hash.update(res._data);
return hash.digest('base64');
}
}
};
}
if (!foundContentType) {
server._config.headers['Content-Type'] = function(res) {
if (res._data && res.options.code !== 204)
return res._accept;
};
}
if (!foundACAO) {
server._config.headers['Access-Control-Allow-Origin'] = function(res) {
return '*';
};
}
if (!foundACAM) {
server._config.headers['Access-Control-Allow-Methods'] = function(res) {
if (res._allowedMethods && res._allowedMethods.length)
return res._allowedMethods.join(', ');
};
}
if (!foundACAH) {
server._config.headers['Access-Control-Allow-Headers'] = function(res) {
return [
'Accept',
'Content-Type',
'Content-Length',
'Date',
'X-Api-Version'
].join(', ');
};
}
if (!foundACEH) {
server._config.headers['Access-Control-Expose-Headers'] = function(res) {
return [
'X-Api-Version',
'X-Request-Id',
'X-Response-Time'
].join(', ');
};
}
return server;
}
};
| modified _parseRequest to only take content handlers from _config.contentHandlers, ie. removed built in ones from this file
| lib/server.js | modified _parseRequest to only take content handlers from _config.contentHandlers, ie. removed built in ones from this file | <ide><path>ib/server.js
<ide>
<ide> var bParams;
<ide> try {
<del> if (contentType === 'application/x-www-form-urlencoded') {
<del> bParams = querystring.parse(request.body) || {};
<del> } else if (contentType === 'application/json') {
<del> bParams = JSON.parse(request.body);
<del> } else if (request._config.contentHandlers[contentType]) {
<del> var fn = request._config.contentHandlers[contentType];
<del> bParams = fn(request.body);
<add> if (request._config.contentHandlers[contentType]) {
<add> bParams = request._config.contentHandlers[contentType](request.body, request, response);
<ide> } else if (contentType) {
<ide> return response.sendError(newError({
<ide> httpCode: HttpCodes.UnsupportedMediaType, |
|
Java | mit | 1f0f5663706d4194947698f68dd7aec7cd872553 | 0 | hpe-idol/java-powerpoint-report,hpautonomy/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpe-idol/find,hpe-idol/find,hpautonomy/find | package com.autonomy.abc.find;
import com.autonomy.abc.config.HostedTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.framework.KnownBug;
import com.autonomy.abc.framework.RelatedTo;
import com.autonomy.abc.selenium.application.HSODFind;
import com.autonomy.abc.selenium.control.Session;
import com.autonomy.abc.selenium.control.Window;
import com.autonomy.abc.selenium.element.FindParametricCheckbox;
import com.autonomy.abc.selenium.find.Find;
import com.autonomy.abc.selenium.find.FindResultsPage;
import com.autonomy.abc.selenium.indexes.Index;
import com.autonomy.abc.selenium.keywords.KeywordFilter;
import com.autonomy.abc.selenium.keywords.KeywordService;
import com.autonomy.abc.selenium.language.Language;
import com.autonomy.abc.selenium.page.HSOElementFactory;
import com.autonomy.abc.selenium.page.search.DocumentViewer;
import com.autonomy.abc.selenium.page.search.SearchBase;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.autonomy.abc.selenium.promotions.*;
import com.autonomy.abc.selenium.search.FindSearchResult;
import com.autonomy.abc.selenium.search.IndexFilter;
import com.autonomy.abc.selenium.search.ParametricFilter;
import com.autonomy.abc.selenium.search.StringDateFilter;
import com.autonomy.abc.selenium.util.ElementUtil;
import com.autonomy.abc.selenium.util.Errors;
import com.autonomy.abc.selenium.util.Locator;
import com.autonomy.abc.selenium.util.Waits;
import com.google.common.collect.Lists;
import com.hp.autonomy.hod.client.api.authentication.ApiKey;
import com.hp.autonomy.hod.client.api.authentication.AuthenticationService;
import com.hp.autonomy.hod.client.api.authentication.AuthenticationServiceImpl;
import com.hp.autonomy.hod.client.api.authentication.TokenType;
import com.hp.autonomy.hod.client.api.resource.ResourceIdentifier;
import com.hp.autonomy.hod.client.api.textindex.query.fields.*;
import com.hp.autonomy.hod.client.config.HodServiceConfig;
import com.hp.autonomy.hod.client.error.HodErrorException;
import com.hp.autonomy.hod.client.token.TokenProxy;
import org.apache.commons.collections4.ListUtils;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.*;
import java.util.regex.Pattern;
import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.framework.ABCAssert.verifyThat;
import static com.autonomy.abc.matchers.ElementMatchers.*;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestBase.fail;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.openqa.selenium.lift.Matchers.displayed;
public class FindITCase extends HostedTestBase {
private Find find;
private FindResultsPage results;
private final Matcher<String> noDocs = containsString(Errors.Search.NO_RESULTS);
private PromotionService<?> promotionService;
private KeywordService keywordService;
private Window searchWindow;
private Window findWindow;
public FindITCase(TestConfig config) {
super(config);
}
@Before
public void setUp(){
promotionService = getApplication().promotionService();
keywordService = getApplication().keywordService();
searchWindow = getMainSession().getActiveWindow();
findWindow = getMainSession().openWindow(config.getFindUrl());
find = getElementFactory().getFindPage();
results = find.getResultsPage();
}
@Test
public void testSendKeys() throws InterruptedException {
String searchTerm = "Fred is a chimpanzee";
find.search(searchTerm);
assertThat(find.getSearchBoxTerm(), is(searchTerm));
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testPdfContentTypeValue(){
find.search("red star");
find.filterBy(new ParametricFilter("Content Type", "APPLICATION/PDF"));
for(String type : results.getDisplayedDocumentsDocumentTypes()){
assertThat(type,containsString("pdf"));
}
}
@Test
public void testHtmlContentTypeValue(){
find.search("red star");
find.filterBy(new ParametricFilter("Content Type", "TEXT/HTML"));
for(String type : results.getDisplayedDocumentsDocumentTypes()){
assertThat(type,containsString("html"));
}
}
@Test
public void testFilteringByParametricValues(){
find.search("Alexis");
find.waitForParametricValuesToLoad();
int expectedResults = plainTextCheckbox().getResultsCount();
plainTextCheckbox().check();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
verifyParametricFields(plainTextCheckbox(), expectedResults);
verifyTicks(true, false);
expectedResults = plainTextCheckbox().getResultsCount();
simpsonsArchiveCheckbox().check();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
verifyParametricFields(plainTextCheckbox(), expectedResults); //TODO Maybe change plainTextCheckbox to whichever has the higher value??
verifyTicks(true, true);
plainTextCheckbox().uncheck();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
expectedResults = simpsonsArchiveCheckbox().getResultsCount();
verifyParametricFields(simpsonsArchiveCheckbox(), expectedResults);
verifyTicks(false, true);
}
private void verifyParametricFields(FindParametricCheckbox checked, int expectedResults){
Waits.loadOrFadeWait();
int resultsTotal = results.getResultTitles().size();
int checkboxResults = checked.getResultsCount();
verifyThat(resultsTotal, is(Math.min(expectedResults, 30)));
verifyThat(checkboxResults, is(expectedResults));
}
private void verifyTicks(boolean plainChecked, boolean simpsonsChecked){
verifyThat(plainTextCheckbox().isChecked(), is(plainChecked));
verifyThat(simpsonsArchiveCheckbox().isChecked(), is(simpsonsChecked));
}
private FindParametricCheckbox simpsonsArchiveCheckbox(){
return results.parametricTypeCheckbox("Source Connector", "SIMPSONSARCHIVE");
}
private FindParametricCheckbox plainTextCheckbox(){
return results.parametricTypeCheckbox("Content Type", "TEXT/PLAIN");
}
@Test
public void testUnselectingContentTypeQuicklyDoesNotLeadToError() {
find.search("wolf");
results.parametricTypeCheckbox("Content Type", "TEXT/HTML").check();
Waits.loadOrFadeWait();
results.parametricTypeCheckbox("Content Type", "TEXT/HTML").uncheck();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testSearch(){
find.search("Red");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testSortByRelevance() {
searchWindow.activate();
getElementFactory().getTopNavBar().search("stars bbc");
SearchPage searchPage = getElementFactory().getSearchPage();
searchPage.sortBy(SearchBase.Sort.RELEVANCE);
List<String> searchTitles = searchPage.getSearchResultTitles(30);
findWindow.activate();
find.search("stars bbc");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getResultTitles(), is(searchTitles));
}
@Test
public void testSortByDate(){
searchWindow.activate();
getElementFactory().getTopNavBar().search("stars bbc");
SearchPage searchPage = getElementFactory().getSearchPage();
searchPage.sortBy(SearchBase.Sort.DATE);
List<String> searchTitles = searchPage.getSearchResultTitles(30);
findWindow.activate();
find.search("stars bbc");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
find.sortBy(SearchBase.Sort.DATE);
assertThat(results.getResultTitles(), is(searchTitles));
}
//TODO ALL RELATED CONCEPTS TESTS - probably better to check if text is not("Loading...") rather than not("")
@Test
public void testRelatedConceptsHasResults(){
find.search("Danye West");
for (WebElement concept : results.relatedConcepts()) {
assertThat(concept, hasTextThat(not(isEmptyOrNullString())));
}
}
@Test
public void testRelatedConceptsNavigateOnClick(){
find.search("Red");
WebElement topRelatedConcept = results.relatedConcepts().get(0);
String concept = topRelatedConcept.getText();
topRelatedConcept.click();
assertThat(getDriver().getCurrentUrl(), containsString(concept));
assertThat(find.getSearchBoxTerm(), containsString(concept));
}
@Test
@KnownBug("CCUK-3498")
public void testRelatedConceptsHover(){
find.search("Find");
WebElement popover = results.hoverOverRelatedConcept(0);
verifyThat(popover, hasTextThat(not(isEmptyOrNullString())));
verifyThat(popover.getText(), not(containsString("QueryText-Placeholder")));
results.unhover();
}
@Test
public void testPinToPosition(){
String search = "red";
String trigger = "mate";
PinToPositionPromotion promotion = new PinToPositionPromotion(1, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
String documentTitle = promotionService.setUpPromotion(promotion, search, 1).get(0);
findWindow.activate();
find.search(trigger);
assertThat(results.searchResult(1).getTitleString(), is(documentTitle));
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testPinToPositionThree(){
String search = "red";
String trigger = "mate";
PinToPositionPromotion promotion = new PinToPositionPromotion(3, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
String documentTitle = promotionService.setUpPromotion(promotion, search, 1).get(0);
findWindow.activate();
find.search(trigger);
assertThat(results.searchResult(3).getTitleString(), is(documentTitle));
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testSpotlightPromotions(){
String search = "Proper";
String trigger = "Prim";
SpotlightPromotion spotlight = new SpotlightPromotion(trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
List<String> createdPromotions = promotionService.setUpPromotion(spotlight, search, 3);
findWindow.activate();
find.search(trigger);
List<String> findPromotions = results.getPromotionsTitles();
assertThat(findPromotions, not(empty()));
assertThat(createdPromotions, everyItem(isIn(findPromotions)));
promotionShownCorrectly(results.promotions());
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testStaticPromotions(){
String title = "TITLE";
String content = "CONTENT";
String trigger = "LOVE";
StaticPromotion promotion = new StaticPromotion(title, content, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
((HSOPromotionService) promotionService).setUpStaticPromotion(promotion);
findWindow.activate();
find.search(trigger);
List<FindSearchResult> promotions = results.promotions();
assertThat(promotions.size(), is(1));
FindSearchResult staticPromotion = promotions.get(0);
assertThat(staticPromotion.getTitleString(), is(title));
assertThat(staticPromotion.getDescription(), containsString(content));
promotionShownCorrectly(staticPromotion);
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testDynamicPromotions(){
int resultsToPromote = 13;
String search = "kittens";
String trigger = "Rugby";
DynamicPromotion dynamicPromotion = new DynamicPromotion(resultsToPromote, trigger);
searchWindow.activate();
promotionService.deleteAll();
try{
List<String> promotedDocumentTitles = promotionService.setUpPromotion(dynamicPromotion, search, resultsToPromote);
findWindow.activate();
find.search(trigger);
verifyThat(promotedDocumentTitles, everyItem(isIn(results.getPromotionsTitles())));
promotionShownCorrectly(results.promotions());
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
private void promotionShownCorrectly (FindSearchResult promotion){
verifyThat(promotion.isPromoted(), is(true));
verifyThat(promotion.star(), displayed());
}
private void promotionShownCorrectly (List<FindSearchResult> promotions){
for(FindSearchResult promotion : promotions){
promotionShownCorrectly(promotion);
}
}
@Test
@KnownBug("CSA-1767 - footer not hidden properly")
@RelatedTo({"CSA-946", "CSA-1656", "CSA-1657", "CSA-1908"})
public void testMetadata(){
find.search("stars");
find.filterBy(new IndexFilter(Index.DEFAULT));
for(FindSearchResult searchResult : results.getResults(5)){
String url = searchResult.getReference();
try {
searchResult.title().click();
} catch (WebDriverException e) {
fail("Could not click on title - most likely CSA-1767");
}
DocumentViewer docViewer = DocumentViewer.make(getDriver());
assertThat(docViewer.getDomain(), is(getCurrentUser().getDomain()));
assertThat(docViewer.getIndex(), is(Index.DEFAULT));
assertThat(docViewer.getReference(), is(url));
docViewer.close();
}
}
@Test
public void testAuthor(){
String author = "FIFA.COM";
find.search("football");
find.filterBy(new IndexFilter("Fifa"));
find.filterBy(new ParametricFilter("Author", author));
List<FindSearchResult> searchResults = results.getResults();
for(int i = 0; i < 6; i++){
searchResults.get(i).title().click();
DocumentViewer documentViewer = DocumentViewer.make(getDriver());
verifyThat(documentViewer.getAuthor(), equalToIgnoringCase(author));
documentViewer.close();
}
}
@Test
public void testFilterByIndex(){
find.search("Sam");
WebElement title = results.searchResult(1).title();
String titleString = title.getText();
title.click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
Index index = docViewer.getIndex();
docViewer.close();
find.filterBy(new IndexFilter(index));
assertThat(results.searchResult(1).getTitleString(), is(titleString));
}
@Test
public void testFilterByIndexOnlyContainsFilesFromThatIndex(){
find.search("Happy");
// TODO: what if this index has no results?
String indexTitle = find.getPrivateIndexNames().get(2);
find.filterBy(new IndexFilter(indexTitle));
results.searchResult(1).title().click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
do{
assertThat(docViewer.getIndex().getDisplayName(), is(indexTitle));
docViewer.next();
} while (docViewer.getCurrentDocumentNumber() != 1);
}
@Test
public void testQuicklyDoubleClickingIndexDoesNotLeadToError(){
find.search("index");
// async filters
new IndexFilter(Index.DEFAULT).apply(find);
IndexFilter.PRIVATE.apply(find);
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.resultsDiv().getText().toLowerCase(), not(containsString("an error occurred")));
}
@Test
public void testPreDefinedWeekHasSameResultsAsCustomWeek(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.WEEK);
}
@Test
public void testPreDefinedMonthHasSameResultsAsCustomMonth(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.MONTH);
}
@Test
public void testPreDefinedYearHasSameResultsAsCustomYear(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.YEAR);
}
private void preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum period){
find.search("Rugby");
results.toggleDateSelection(period);
List<String> preDefinedResults = results.getResultTitles();
find.filterBy(new StringDateFilter().from(getDate(period)));
List<String> customResults = results.getResultTitles();
assertThat(preDefinedResults, is(customResults));
}
private Date getDate(FindResultsPage.DateEnum period) {
Calendar cal = Calendar.getInstance();
if (period != null) {
switch (period) {
case WEEK:
cal.add(Calendar.DATE,-7);
break;
case MONTH:
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
break;
case YEAR:
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 1);
break;
}
}
return cal.getTime();
}
@Ignore //TODO seems to have broken
@Test
public void testAllParametricFieldsAreShown() throws HodErrorException {
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setProxy(new HttpHost("proxy.sdc.hp.com", 8080));
final HodServiceConfig config = new HodServiceConfig.Builder("https://api.int.havenondemand.com")
.setHttpClient(httpClientBuilder.build()) // use a custom Apache HttpClient - useful if you're behind a proxy
.build();
final AuthenticationService authenticationService = new AuthenticationServiceImpl(config);
final RetrieveIndexFieldsService retrieveIndexFieldsService = new RetrieveIndexFieldsServiceImpl(config);
final TokenProxy tokenProxy = authenticationService.authenticateApplication(
new ApiKey("098b8420-f85f-4164-b8a8-42263e9405a1"),
"733d64e8-41f7-4c46-a1c8-60d083255159",
getCurrentUser().getDomain(),
TokenType.simple
);
Set<String> parametricFields = new HashSet<>();
find.search("Something");
for (String indexName : find.getPrivateIndexNames()) {
RetrieveIndexFieldsResponse retrieveIndexFieldsResponse = retrieveIndexFieldsService.retrieveIndexFields(tokenProxy,
new ResourceIdentifier(getCurrentUser().getDomain(), indexName), new RetrieveIndexFieldsRequestBuilder().setFieldType(FieldType.parametric));
parametricFields.addAll(retrieveIndexFieldsResponse.getAllFields());
}
for(String field : parametricFields) {
try {
assertTrue(results.parametricContainer(field).isDisplayed());
} catch (ElementNotVisibleException | NotFoundException e) {
fail("Could not find field '"+field+"'");
}
}
}
@Test
@KnownBug("CSA-1767 - footer not hidden properly")
public void testViewDocumentsOpenFromFind(){
find.search("Review");
for(FindSearchResult result : results.getResults(5)){
try {
ElementUtil.scrollIntoViewAndClick(result.title(), getDriver());
} catch (WebDriverException e){
fail("Could not click on title - most likely CSA-1767");
}
DocumentViewer docViewer = DocumentViewer.make(getDriver());
verifyDocumentViewer(docViewer);
docViewer.close();
}
}
@Test
public void testViewDocumentsOpenWithArrows(){
find.search("Review");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
results.searchResult(1).title().click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
do{
verifyDocumentViewer(docViewer);
docViewer.next();
} while (docViewer.getCurrentDocumentNumber() != 1);
}
private void verifyDocumentViewer(DocumentViewer docViewer) {
verifyThat("document visible", docViewer, displayed());
verifyThat("next button visible", docViewer.nextButton(), displayed());
verifyThat("previous button visible", docViewer.prevButton(), displayed());
String handle = getDriver().getWindowHandle();
getDriver().switchTo().frame(docViewer.frame());
//TODO these aren't working properly - did Fred not fix these?
verifyThat("no backend error", getDriver().findElements(new Locator().withTagName("h1").containingText("500")), empty());
verifyThat("no view server error", getDriver().findElements(new Locator().withTagName("h2").containingCaseInsensitive("error")), empty());
getDriver().switchTo().window(handle);
}
@Test
public void testDateRemainsWhenClosingAndReopeningDateFilters(){
find.search("Corbyn");
Date start = getDate(FindResultsPage.DateEnum.MONTH);
Date end = getDate(FindResultsPage.DateEnum.WEEK);
find.filterBy(new StringDateFilter().from(start).until(end));
Waits.loadOrFadeWait();
for (int unused = 0; unused < 3; unused++) {
results.toggleDateSelection(FindResultsPage.DateEnum.CUSTOM);
Waits.loadOrFadeWait();
}
assertThat(find.fromDateInput().getValue(), is(find.formatInputDate(start)));
assertThat(find.untilDateInput().getValue(), is(find.formatInputDate(end)));
}
@Test
public void testFileTypes(){
find.search("love ");
for(FileType f : FileType.values()) {
find.filterBy(new ParametricFilter("Content Type",f.getSidebarString()));
for(FindSearchResult result : results.getResults()){
assertThat(result.getIcon().getAttribute("class"), containsString(f.getFileIconString()));
}
find.filterBy(new ParametricFilter("Content Type",f.getSidebarString()));
}
}
@Test
public void testSynonyms() throws InterruptedException {
String nonsense = "iuhdsafsaubfdja";
searchWindow.activate();
keywordService.deleteAll(KeywordFilter.ALL);
Waits.loadOrFadeWait();
findWindow.activate();
find.search(nonsense);
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText(), noDocs);
find.search("Cat");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText(), not(noDocs));
searchWindow.activate();
keywordService.addSynonymGroup(Language.ENGLISH, "cat", nonsense);
/* need a separate session due to caching */
Session secondSession = getSessionRegistry().startSession(config.getFindUrl());
try {
Find otherFind = initialiseSession(secondSession);
otherFind.search("Cat");
FindResultsPage otherResults = otherFind.getResultsPage();
String firstTitle = otherResults.searchResult(1).getTitleString();
otherFind.search(nonsense);
assertThat(otherResults.getText(), not(noDocs));
verifyThat(otherResults.searchResult(1).getTitleString(), is(firstTitle));
} finally {
getSessionRegistry().endSession(secondSession);
}
}
@Test
public void testBlacklist() throws InterruptedException {
searchWindow.activate();
keywordService.deleteAll(KeywordFilter.ALL);
Waits.loadOrFadeWait();
findWindow.activate();
find.search("Cat");
assertThat(results.getText(), not(noDocs));
find.search("Holder");
searchWindow.activate();
keywordService.addBlacklistTerms(Language.ENGLISH, "cat");
/* need a separate session due to caching */
Session secondSession = getSessionRegistry().startSession(config.getFindUrl());
try {
Find otherFind = initialiseSession(secondSession);
otherFind.search("Cat");
assertThat(otherFind.getResultsPage(), hasTextThat(noDocs));
} finally {
getSessionRegistry().endSession(secondSession);
}
}
// TODO: this does not belong here
private Find initialiseSession(Session session) {
HSOElementFactory otherElementFactory = new HSODFind(session.getActiveWindow()).elementFactory();
loginTo(otherElementFactory.getFindLoginPage(), session.getDriver(), config.getDefaultUser());
return otherElementFactory.getFindPage();
}
@Test @Ignore("Not implemented")
public void testOverlappingSynonyms(){}
@Test
public void testBooleanOperators(){
String termOne = "musketeers";
String termTwo = "\"dearly departed\"";
find.search(termOne);
List<String> musketeersSearchResults = results.getResultTitles();
int numberOfMusketeersResults = musketeersSearchResults.size();
find.search(termTwo);
List<String> dearlyDepartedSearchResults = results.getResultTitles();
int numberOfDearlyDepartedResults = dearlyDepartedSearchResults.size();
find.search(termOne + " AND " + termTwo);
List<String> andResults = results.getResultTitles();
int numberOfAndResults = andResults.size();
assertThat(numberOfMusketeersResults,greaterThanOrEqualTo(numberOfAndResults));
assertThat(numberOfDearlyDepartedResults, greaterThanOrEqualTo(numberOfAndResults));
String[] andResultsArray = andResults.toArray(new String[andResults.size()]);
assertThat(musketeersSearchResults, hasItems(andResultsArray));
assertThat(dearlyDepartedSearchResults, hasItems(andResultsArray));
find.search(termOne + " OR " + termTwo);
List<String> orResults = results.getResultTitles();
Set<String> concatenatedResults = new HashSet<>(ListUtils.union(musketeersSearchResults, dearlyDepartedSearchResults));
assertThat(orResults.size(), is(concatenatedResults.size()));
assertThat(orResults, containsInAnyOrder(concatenatedResults.toArray()));
find.search(termOne + " XOR " + termTwo);
List<String> xorResults = results.getResultTitles();
concatenatedResults.removeAll(andResults);
assertThat(xorResults.size(), is(concatenatedResults.size()));
assertThat(xorResults, containsInAnyOrder(concatenatedResults.toArray()));
find.search(termOne + " NOT " + termTwo);
List<String> notTermTwo = results.getResultTitles();
Set<String> t1NotT2 = new HashSet<>(concatenatedResults);
t1NotT2.removeAll(dearlyDepartedSearchResults);
assertThat(notTermTwo.size(), is(t1NotT2.size()));
assertThat(notTermTwo, containsInAnyOrder(t1NotT2.toArray()));
find.search(termTwo + " NOT " + termOne);
List<String> notTermOne = results.getResultTitles();
Set<String> t2NotT1 = new HashSet<>(concatenatedResults);
t2NotT1.removeAll(musketeersSearchResults);
assertThat(notTermOne.size(), is(t2NotT1.size()));
assertThat(notTermOne, containsInAnyOrder(t2NotT1.toArray()));
}
//DUPLICATE SEARCH TEST (almost)
@Test
public void testCorrectErrorMessageDisplayed() {
//TODO: map error messages to application type
List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR");
List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets
for (final String searchTerm : boolOperators) {
find.search(searchTerm);
verifyThat("Correct error message for searchterm: " + searchTerm, find.getText(), containsString(Errors.Search.OPERATORS));
}
for (final String searchTerm : stopWords) {
find.search(searchTerm);
verifyThat("Correct error message for searchterm: " + searchTerm, find.getText(), containsString(Errors.Search.STOPWORDS));
}
}
//DUPLICATE SEARCH TEST
@Test
public void testAllowSearchOfStringsThatContainBooleansWithinThem() {
final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED");
for (final String hiddenBooleansProximity : hiddenBooleansProximities) {
find.search(hiddenBooleansProximity);
Waits.loadOrFadeWait();
assertThat(find.getText(), not(containsString(Errors.Search.GENERAL)));
}
}
//DUPLICATE
@Test
public void testSearchParentheses() {
List<String> testSearchTerms = Arrays.asList("(",")",") (",")war"); //"()" appears to be fine
for(String searchTerm : testSearchTerms){
find.search(searchTerm);
assertThat(results, containsText(Errors.Search.OPERATORS));
}
}
//DUPLICATE
@Test
@KnownBug({"IOD-8454","CCUK-3634"})
public void testSearchQuotationMarks() {
List<String> testSearchTerms = Arrays.asList("\"","","\"word","\" word","\" wo\"rd\""); //"\"\"" seems okay and " "
for (String searchTerm : testSearchTerms){
find.search(searchTerm);
Waits.loadOrFadeWait();
assertThat(results, containsText(Errors.Search.QUOTES));
}
}
//DUPLICATE
@Test
public void testWhitespaceSearch() {
find.search(" ");
assertThat(results, containsText(Errors.Search.STOPWORDS));
}
@Test
@KnownBug("CSA-1577")
public void testClickingCustomDateFilterDoesNotRefreshResults(){
find.search("O Captain! My Captain!");
// may not happen the first time
for (int unused = 0; unused < 5; unused++) {
results.toggleDateSelection(FindResultsPage.DateEnum.CUSTOM);
assertThat(results.resultsDiv().getText(), not(containsString("Loading")));
}
}
@Test
@KnownBug("CSA-1665")
public void testSearchTermInResults(){
String searchTerm = "Tiger";
find.search(searchTerm);
for(WebElement searchElement : getDriver().findElements(By.xpath("//*[not(self::h4) and contains(text(),'" + searchTerm + "')]"))){
if(searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(searchElement.getText(), containsString(searchTerm));
}
verifyThat(searchElement, not(hasTagName("a")));
verifyThat(searchElement, hasClass("search-text"));
}
}
// TODO: testMultiWordSearchTermInResults
@Test
public void testRelatedConceptsInResults(){
find.search("Tiger");
for(WebElement relatedConceptLink : results.relatedConcepts()){
String relatedConcept = relatedConceptLink.getText();
for (WebElement relatedConceptElement : getDriver().findElements(By.xpath("//*[contains(@class,'middle-container')]//*[not(self::h4) and contains(text(),'" + relatedConcept + "')]"))) {
if (relatedConceptElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(relatedConceptElement.getText(), containsString(relatedConcept));
}
verifyThat(relatedConceptElement, hasTagName("a"));
verifyThat(relatedConceptElement, hasClass("clickable"));
}
}
}
@Test
public void testSimilarDocumentsShowUp(){
find.search("Doe");
for (WebElement similarResultLink : Lists.reverse(results.similarResultLinks())) {
similarResultLink.click();
WebElement popover = results.popover();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElement(popover, "Loading")));
assertThat(popover.findElement(By.tagName("p")).getText(), not("An error occurred fetching similar documents"));
for(WebElement similarResult : popover.findElements(By.tagName("li"))){
assertThat(similarResult.findElement(By.tagName("a")).getText(), not(isEmptyString()));
assertThat(similarResult.findElement(By.tagName("p")).getText(), not(isEmptyString()));
}
}
}
@Test
@KnownBug("CSA-1630")
public void testAllPromotedDocumentsHaveTitles(){
searchWindow.activate();
PromotionService promotionService = getApplication().promotionService();
try {
promotionService.setUpPromotion(new SpotlightPromotion(Promotion.SpotlightType.HOTWIRE, "Tiger"), "scg-2", 10);
findWindow.activate();
find.search("Tiger");
for(String title : results.getPromotionsTitles()){
assertThat(title, is(not("")));
}
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
@KnownBug("CSA-1763")
public void testPublicIndexesNotSelectedByDefault(){
find.search("Marina and the Diamonds");
verifyThat(find.getSelectedPublicIndexes().size(), is(0));
}
@Test
@KnownBug("CSA-2082")
public void testAutoScroll(){
find.search("my very easy method just speeds up naming ");
verifyThat(results.getResults().size(), lessThanOrEqualTo(30));
scrollToBottom();
verifyThat(results.getResults().size(), allOf(greaterThanOrEqualTo(30), lessThanOrEqualTo(60)));
scrollToBottom();
verifyThat(results.getResults().size(), allOf(greaterThanOrEqualTo(60), lessThanOrEqualTo(90)));
List<String> titles = results.getResultTitles();
Set<String> titlesSet = new HashSet<>(titles);
verifyThat("No duplicate titles", titles.size(), is(titlesSet.size()));
}
@Test
public void testViewportSearchResultNumbers(){
find.search("Messi");
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(30);
scrollToBottom();
results.getResult(31).title().click();
verifyDocViewerTotalDocuments(60);
scrollToBottom();
results.getResult(61).title().click();
verifyDocViewerTotalDocuments(90);
}
@Test
@KnownBug("CCUK-3647")
public void testLessThan30ResultsDoesntAttemptToLoadMore() {
find.search("roland garros");
find.filterBy(new IndexFilter("fifa"));
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(lessThanOrEqualTo(30));
scrollToBottom();
verifyThat(results.resultsDiv(), not(containsText("results found")));
}
@Test
public void testBetween30And60Results(){
find.search("idol");
find.filterBy(new IndexFilter("sitesearch"));
scrollToBottom();
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(lessThanOrEqualTo(60));
verifyThat(results.resultsDiv(), containsText("No more results found"));
}
@Test
public void testNoResults(){
find.search("thissearchwillalmostcertainlyreturnnoresults");
verifyThat(results.resultsDiv(), containsText("No results found"));
scrollToBottom();
int i = 0;
Pattern p = Pattern.compile("results found");
java.util.regex.Matcher m = p.matcher(results.resultsDiv().getText());
while(m.find()){
i++;
}
verifyThat("Only one message showing at the bottom of search results", i, is(1));
}
private void scrollToBottom() {
for(int i = 0; i < 10; i++){
new Actions(getDriver()).sendKeys(Keys.PAGE_DOWN).perform();
}
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
}
private void verifyDocViewerTotalDocuments(int docs){
verifyDocViewerTotalDocuments(is(docs));
}
private void verifyDocViewerTotalDocuments(Matcher matcher){
DocumentViewer docViewer = DocumentViewer.make(getDriver());
verifyThat(docViewer.getTotalDocumentsNumber(), matcher);
docViewer.close();
}
private enum FileType {
HTML("TEXT/HTML","html"),
PDF("APPLICATION/PDF","pdf"),
PLAIN("TEXT/PLAIN","file");
private final String sidebarString;
private final String fileIconString;
FileType(String sidebarString, String fileIconString){
this.sidebarString = sidebarString;
this.fileIconString = fileIconString;
}
public String getFileIconString() {
return fileIconString;
}
public String getSidebarString() {
return sidebarString;
}
}
}
| integration-tests-hosted/src/test/java/com/autonomy/abc/find/FindITCase.java | package com.autonomy.abc.find;
import com.autonomy.abc.config.HostedTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.framework.KnownBug;
import com.autonomy.abc.framework.RelatedTo;
import com.autonomy.abc.selenium.application.HSODFind;
import com.autonomy.abc.selenium.control.Session;
import com.autonomy.abc.selenium.control.Window;
import com.autonomy.abc.selenium.element.FindParametricCheckbox;
import com.autonomy.abc.selenium.find.Find;
import com.autonomy.abc.selenium.find.FindResultsPage;
import com.autonomy.abc.selenium.indexes.Index;
import com.autonomy.abc.selenium.keywords.KeywordFilter;
import com.autonomy.abc.selenium.keywords.KeywordService;
import com.autonomy.abc.selenium.language.Language;
import com.autonomy.abc.selenium.page.HSOElementFactory;
import com.autonomy.abc.selenium.page.search.DocumentViewer;
import com.autonomy.abc.selenium.page.search.SearchBase;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.autonomy.abc.selenium.promotions.*;
import com.autonomy.abc.selenium.search.FindSearchResult;
import com.autonomy.abc.selenium.search.IndexFilter;
import com.autonomy.abc.selenium.search.ParametricFilter;
import com.autonomy.abc.selenium.search.StringDateFilter;
import com.autonomy.abc.selenium.util.ElementUtil;
import com.autonomy.abc.selenium.util.Errors;
import com.autonomy.abc.selenium.util.Locator;
import com.autonomy.abc.selenium.util.Waits;
import com.google.common.collect.Lists;
import com.hp.autonomy.hod.client.api.authentication.ApiKey;
import com.hp.autonomy.hod.client.api.authentication.AuthenticationService;
import com.hp.autonomy.hod.client.api.authentication.AuthenticationServiceImpl;
import com.hp.autonomy.hod.client.api.authentication.TokenType;
import com.hp.autonomy.hod.client.api.resource.ResourceIdentifier;
import com.hp.autonomy.hod.client.api.textindex.query.fields.*;
import com.hp.autonomy.hod.client.config.HodServiceConfig;
import com.hp.autonomy.hod.client.error.HodErrorException;
import com.hp.autonomy.hod.client.token.TokenProxy;
import org.apache.commons.collections4.ListUtils;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.*;
import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.framework.ABCAssert.verifyThat;
import static com.autonomy.abc.matchers.ElementMatchers.*;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestBase.fail;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.openqa.selenium.lift.Matchers.displayed;
public class FindITCase extends HostedTestBase {
private Find find;
private FindResultsPage results;
private final Matcher<String> noDocs = containsString(Errors.Search.NO_RESULTS);
private PromotionService<?> promotionService;
private KeywordService keywordService;
private Window searchWindow;
private Window findWindow;
public FindITCase(TestConfig config) {
super(config);
}
@Before
public void setUp(){
promotionService = getApplication().promotionService();
keywordService = getApplication().keywordService();
searchWindow = getMainSession().getActiveWindow();
findWindow = getMainSession().openWindow(config.getFindUrl());
find = getElementFactory().getFindPage();
results = find.getResultsPage();
}
@Test
public void testSendKeys() throws InterruptedException {
String searchTerm = "Fred is a chimpanzee";
find.search(searchTerm);
assertThat(find.getSearchBoxTerm(), is(searchTerm));
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testPdfContentTypeValue(){
find.search("red star");
find.filterBy(new ParametricFilter("Content Type", "APPLICATION/PDF"));
for(String type : results.getDisplayedDocumentsDocumentTypes()){
assertThat(type,containsString("pdf"));
}
}
@Test
public void testHtmlContentTypeValue(){
find.search("red star");
find.filterBy(new ParametricFilter("Content Type", "TEXT/HTML"));
for(String type : results.getDisplayedDocumentsDocumentTypes()){
assertThat(type,containsString("html"));
}
}
@Test
public void testFilteringByParametricValues(){
find.search("Alexis");
find.waitForParametricValuesToLoad();
int expectedResults = plainTextCheckbox().getResultsCount();
plainTextCheckbox().check();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
verifyParametricFields(plainTextCheckbox(), expectedResults);
verifyTicks(true, false);
expectedResults = plainTextCheckbox().getResultsCount();
simpsonsArchiveCheckbox().check();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
verifyParametricFields(plainTextCheckbox(), expectedResults); //TODO Maybe change plainTextCheckbox to whichever has the higher value??
verifyTicks(true, true);
plainTextCheckbox().uncheck();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
expectedResults = simpsonsArchiveCheckbox().getResultsCount();
verifyParametricFields(simpsonsArchiveCheckbox(), expectedResults);
verifyTicks(false, true);
}
private void verifyParametricFields(FindParametricCheckbox checked, int expectedResults){
Waits.loadOrFadeWait();
int resultsTotal = results.getResultTitles().size();
int checkboxResults = checked.getResultsCount();
verifyThat(resultsTotal, is(Math.min(expectedResults, 30)));
verifyThat(checkboxResults, is(expectedResults));
}
private void verifyTicks(boolean plainChecked, boolean simpsonsChecked){
verifyThat(plainTextCheckbox().isChecked(), is(plainChecked));
verifyThat(simpsonsArchiveCheckbox().isChecked(), is(simpsonsChecked));
}
private FindParametricCheckbox simpsonsArchiveCheckbox(){
return results.parametricTypeCheckbox("Source Connector", "SIMPSONSARCHIVE");
}
private FindParametricCheckbox plainTextCheckbox(){
return results.parametricTypeCheckbox("Content Type", "TEXT/PLAIN");
}
@Test
public void testUnselectingContentTypeQuicklyDoesNotLeadToError() {
find.search("wolf");
results.parametricTypeCheckbox("Content Type", "TEXT/HTML").check();
Waits.loadOrFadeWait();
results.parametricTypeCheckbox("Content Type", "TEXT/HTML").uncheck();
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testSearch(){
find.search("Red");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText().toLowerCase(), not(containsString("error")));
}
@Test
public void testSortByRelevance() {
searchWindow.activate();
getElementFactory().getTopNavBar().search("stars bbc");
SearchPage searchPage = getElementFactory().getSearchPage();
searchPage.sortBy(SearchBase.Sort.RELEVANCE);
List<String> searchTitles = searchPage.getSearchResultTitles(30);
findWindow.activate();
find.search("stars bbc");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getResultTitles(), is(searchTitles));
}
@Test
public void testSortByDate(){
searchWindow.activate();
getElementFactory().getTopNavBar().search("stars bbc");
SearchPage searchPage = getElementFactory().getSearchPage();
searchPage.sortBy(SearchBase.Sort.DATE);
List<String> searchTitles = searchPage.getSearchResultTitles(30);
findWindow.activate();
find.search("stars bbc");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
find.sortBy(SearchBase.Sort.DATE);
assertThat(results.getResultTitles(), is(searchTitles));
}
//TODO ALL RELATED CONCEPTS TESTS - probably better to check if text is not("Loading...") rather than not("")
@Test
public void testRelatedConceptsHasResults(){
find.search("Danye West");
for (WebElement concept : results.relatedConcepts()) {
assertThat(concept, hasTextThat(not(isEmptyOrNullString())));
}
}
@Test
public void testRelatedConceptsNavigateOnClick(){
find.search("Red");
WebElement topRelatedConcept = results.relatedConcepts().get(0);
String concept = topRelatedConcept.getText();
topRelatedConcept.click();
assertThat(getDriver().getCurrentUrl(), containsString(concept));
assertThat(find.getSearchBoxTerm(), containsString(concept));
}
@Test
@KnownBug("CCUK-3498")
public void testRelatedConceptsHover(){
find.search("Find");
WebElement popover = results.hoverOverRelatedConcept(0);
verifyThat(popover, hasTextThat(not(isEmptyOrNullString())));
verifyThat(popover.getText(), not(containsString("QueryText-Placeholder")));
results.unhover();
}
@Test
public void testPinToPosition(){
String search = "red";
String trigger = "mate";
PinToPositionPromotion promotion = new PinToPositionPromotion(1, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
String documentTitle = promotionService.setUpPromotion(promotion, search, 1).get(0);
findWindow.activate();
find.search(trigger);
assertThat(results.searchResult(1).getTitleString(), is(documentTitle));
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testPinToPositionThree(){
String search = "red";
String trigger = "mate";
PinToPositionPromotion promotion = new PinToPositionPromotion(3, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
String documentTitle = promotionService.setUpPromotion(promotion, search, 1).get(0);
findWindow.activate();
find.search(trigger);
assertThat(results.searchResult(3).getTitleString(), is(documentTitle));
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testSpotlightPromotions(){
String search = "Proper";
String trigger = "Prim";
SpotlightPromotion spotlight = new SpotlightPromotion(trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
List<String> createdPromotions = promotionService.setUpPromotion(spotlight, search, 3);
findWindow.activate();
find.search(trigger);
List<String> findPromotions = results.getPromotionsTitles();
assertThat(findPromotions, not(empty()));
assertThat(createdPromotions, everyItem(isIn(findPromotions)));
promotionShownCorrectly(results.promotions());
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testStaticPromotions(){
String title = "TITLE";
String content = "CONTENT";
String trigger = "LOVE";
StaticPromotion promotion = new StaticPromotion(title, content, trigger);
searchWindow.activate();
promotionService.deleteAll();
try {
((HSOPromotionService) promotionService).setUpStaticPromotion(promotion);
findWindow.activate();
find.search(trigger);
List<FindSearchResult> promotions = results.promotions();
assertThat(promotions.size(), is(1));
FindSearchResult staticPromotion = promotions.get(0);
assertThat(staticPromotion.getTitleString(), is(title));
assertThat(staticPromotion.getDescription(), containsString(content));
promotionShownCorrectly(staticPromotion);
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
public void testDynamicPromotions(){
int resultsToPromote = 13;
String search = "kittens";
String trigger = "Rugby";
DynamicPromotion dynamicPromotion = new DynamicPromotion(resultsToPromote, trigger);
searchWindow.activate();
promotionService.deleteAll();
try{
List<String> promotedDocumentTitles = promotionService.setUpPromotion(dynamicPromotion, search, resultsToPromote);
findWindow.activate();
find.search(trigger);
verifyThat(promotedDocumentTitles, everyItem(isIn(results.getPromotionsTitles())));
promotionShownCorrectly(results.promotions());
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
private void promotionShownCorrectly (FindSearchResult promotion){
verifyThat(promotion.isPromoted(), is(true));
verifyThat(promotion.star(), displayed());
}
private void promotionShownCorrectly (List<FindSearchResult> promotions){
for(FindSearchResult promotion : promotions){
promotionShownCorrectly(promotion);
}
}
@Test
@KnownBug("CSA-1767 - footer not hidden properly")
@RelatedTo({"CSA-946", "CSA-1656", "CSA-1657", "CSA-1908"})
public void testMetadata(){
find.search("stars");
find.filterBy(new IndexFilter(Index.DEFAULT));
for(FindSearchResult searchResult : results.getResults(5)){
String url = searchResult.getReference();
try {
searchResult.title().click();
} catch (WebDriverException e) {
fail("Could not click on title - most likely CSA-1767");
}
DocumentViewer docViewer = DocumentViewer.make(getDriver());
assertThat(docViewer.getDomain(), is(getCurrentUser().getDomain()));
assertThat(docViewer.getIndex(), is(Index.DEFAULT));
assertThat(docViewer.getReference(), is(url));
docViewer.close();
}
}
@Test
public void testAuthor(){
String author = "FIFA.COM";
find.search("football");
find.filterBy(new IndexFilter("Fifa"));
find.filterBy(new ParametricFilter("Author", author));
List<FindSearchResult> searchResults = results.getResults();
for(int i = 0; i < 6; i++){
searchResults.get(i).title().click();
DocumentViewer documentViewer = DocumentViewer.make(getDriver());
verifyThat(documentViewer.getAuthor(), equalToIgnoringCase(author));
documentViewer.close();
}
}
@Test
public void testFilterByIndex(){
find.search("Sam");
WebElement title = results.searchResult(1).title();
String titleString = title.getText();
title.click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
Index index = docViewer.getIndex();
docViewer.close();
find.filterBy(new IndexFilter(index));
assertThat(results.searchResult(1).getTitleString(), is(titleString));
}
@Test
public void testFilterByIndexOnlyContainsFilesFromThatIndex(){
find.search("Happy");
// TODO: what if this index has no results?
String indexTitle = find.getPrivateIndexNames().get(2);
find.filterBy(new IndexFilter(indexTitle));
results.searchResult(1).title().click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
do{
assertThat(docViewer.getIndex().getDisplayName(), is(indexTitle));
docViewer.next();
} while (docViewer.getCurrentDocumentNumber() != 1);
}
@Test
public void testQuicklyDoubleClickingIndexDoesNotLeadToError(){
find.search("index");
// async filters
new IndexFilter(Index.DEFAULT).apply(find);
IndexFilter.PRIVATE.apply(find);
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.resultsDiv().getText().toLowerCase(), not(containsString("an error occurred")));
}
@Test
public void testPreDefinedWeekHasSameResultsAsCustomWeek(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.WEEK);
}
@Test
public void testPreDefinedMonthHasSameResultsAsCustomMonth(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.MONTH);
}
@Test
public void testPreDefinedYearHasSameResultsAsCustomYear(){
preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum.YEAR);
}
private void preDefinedDateFiltersVersusCustomDateFilters(FindResultsPage.DateEnum period){
find.search("Rugby");
results.toggleDateSelection(period);
List<String> preDefinedResults = results.getResultTitles();
find.filterBy(new StringDateFilter().from(getDate(period)));
List<String> customResults = results.getResultTitles();
assertThat(preDefinedResults, is(customResults));
}
private Date getDate(FindResultsPage.DateEnum period) {
Calendar cal = Calendar.getInstance();
if (period != null) {
switch (period) {
case WEEK:
cal.add(Calendar.DATE,-7);
break;
case MONTH:
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
break;
case YEAR:
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 1);
break;
}
}
return cal.getTime();
}
@Ignore //TODO seems to have broken
@Test
public void testAllParametricFieldsAreShown() throws HodErrorException {
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setProxy(new HttpHost("proxy.sdc.hp.com", 8080));
final HodServiceConfig config = new HodServiceConfig.Builder("https://api.int.havenondemand.com")
.setHttpClient(httpClientBuilder.build()) // use a custom Apache HttpClient - useful if you're behind a proxy
.build();
final AuthenticationService authenticationService = new AuthenticationServiceImpl(config);
final RetrieveIndexFieldsService retrieveIndexFieldsService = new RetrieveIndexFieldsServiceImpl(config);
final TokenProxy tokenProxy = authenticationService.authenticateApplication(
new ApiKey("098b8420-f85f-4164-b8a8-42263e9405a1"),
"733d64e8-41f7-4c46-a1c8-60d083255159",
getCurrentUser().getDomain(),
TokenType.simple
);
Set<String> parametricFields = new HashSet<>();
find.search("Something");
for (String indexName : find.getPrivateIndexNames()) {
RetrieveIndexFieldsResponse retrieveIndexFieldsResponse = retrieveIndexFieldsService.retrieveIndexFields(tokenProxy,
new ResourceIdentifier(getCurrentUser().getDomain(), indexName), new RetrieveIndexFieldsRequestBuilder().setFieldType(FieldType.parametric));
parametricFields.addAll(retrieveIndexFieldsResponse.getAllFields());
}
for(String field : parametricFields) {
try {
assertTrue(results.parametricContainer(field).isDisplayed());
} catch (ElementNotVisibleException | NotFoundException e) {
fail("Could not find field '"+field+"'");
}
}
}
@Test
@KnownBug("CSA-1767 - footer not hidden properly")
public void testViewDocumentsOpenFromFind(){
find.search("Review");
for(FindSearchResult result : results.getResults(5)){
try {
ElementUtil.scrollIntoViewAndClick(result.title(), getDriver());
} catch (WebDriverException e){
fail("Could not click on title - most likely CSA-1767");
}
DocumentViewer docViewer = DocumentViewer.make(getDriver());
verifyDocumentViewer(docViewer);
docViewer.close();
}
}
@Test
public void testViewDocumentsOpenWithArrows(){
find.search("Review");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
results.searchResult(1).title().click();
DocumentViewer docViewer = DocumentViewer.make(getDriver());
do{
verifyDocumentViewer(docViewer);
docViewer.next();
} while (docViewer.getCurrentDocumentNumber() != 1);
}
private void verifyDocumentViewer(DocumentViewer docViewer) {
verifyThat("document visible", docViewer, displayed());
verifyThat("next button visible", docViewer.nextButton(), displayed());
verifyThat("previous button visible", docViewer.prevButton(), displayed());
String handle = getDriver().getWindowHandle();
getDriver().switchTo().frame(docViewer.frame());
//TODO these aren't working properly - did Fred not fix these?
verifyThat("no backend error", getDriver().findElements(new Locator().withTagName("h1").containingText("500")), empty());
verifyThat("no view server error", getDriver().findElements(new Locator().withTagName("h2").containingCaseInsensitive("error")), empty());
getDriver().switchTo().window(handle);
}
@Test
public void testDateRemainsWhenClosingAndReopeningDateFilters(){
find.search("Corbyn");
Date start = getDate(FindResultsPage.DateEnum.MONTH);
Date end = getDate(FindResultsPage.DateEnum.WEEK);
find.filterBy(new StringDateFilter().from(start).until(end));
Waits.loadOrFadeWait();
for (int unused = 0; unused < 3; unused++) {
results.toggleDateSelection(FindResultsPage.DateEnum.CUSTOM);
Waits.loadOrFadeWait();
}
assertThat(find.fromDateInput().getValue(), is(find.formatInputDate(start)));
assertThat(find.untilDateInput().getValue(), is(find.formatInputDate(end)));
}
@Test
public void testFileTypes(){
find.search("love ");
for(FileType f : FileType.values()) {
find.filterBy(new ParametricFilter("Content Type",f.getSidebarString()));
for(FindSearchResult result : results.getResults()){
assertThat(result.getIcon().getAttribute("class"), containsString(f.getFileIconString()));
}
find.filterBy(new ParametricFilter("Content Type",f.getSidebarString()));
}
}
@Test
public void testSynonyms() throws InterruptedException {
String nonsense = "iuhdsafsaubfdja";
searchWindow.activate();
keywordService.deleteAll(KeywordFilter.ALL);
Waits.loadOrFadeWait();
findWindow.activate();
find.search(nonsense);
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText(), noDocs);
find.search("Cat");
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
assertThat(results.getText(), not(noDocs));
searchWindow.activate();
keywordService.addSynonymGroup(Language.ENGLISH, "cat", nonsense);
/* need a separate session due to caching */
Session secondSession = getSessionRegistry().startSession(config.getFindUrl());
try {
Find otherFind = initialiseSession(secondSession);
otherFind.search("Cat");
FindResultsPage otherResults = otherFind.getResultsPage();
String firstTitle = otherResults.searchResult(1).getTitleString();
otherFind.search(nonsense);
assertThat(otherResults.getText(), not(noDocs));
verifyThat(otherResults.searchResult(1).getTitleString(), is(firstTitle));
} finally {
getSessionRegistry().endSession(secondSession);
}
}
@Test
public void testBlacklist() throws InterruptedException {
searchWindow.activate();
keywordService.deleteAll(KeywordFilter.ALL);
Waits.loadOrFadeWait();
findWindow.activate();
find.search("Cat");
assertThat(results.getText(), not(noDocs));
find.search("Holder");
searchWindow.activate();
keywordService.addBlacklistTerms(Language.ENGLISH, "cat");
/* need a separate session due to caching */
Session secondSession = getSessionRegistry().startSession(config.getFindUrl());
try {
Find otherFind = initialiseSession(secondSession);
otherFind.search("Cat");
assertThat(otherFind.getResultsPage(), hasTextThat(noDocs));
} finally {
getSessionRegistry().endSession(secondSession);
}
}
// TODO: this does not belong here
private Find initialiseSession(Session session) {
HSOElementFactory otherElementFactory = new HSODFind(session.getActiveWindow()).elementFactory();
loginTo(otherElementFactory.getFindLoginPage(), session.getDriver(), config.getDefaultUser());
return otherElementFactory.getFindPage();
}
@Test @Ignore("Not implemented")
public void testOverlappingSynonyms(){}
@Test
public void testBooleanOperators(){
String termOne = "musketeers";
String termTwo = "\"dearly departed\"";
find.search(termOne);
List<String> musketeersSearchResults = results.getResultTitles();
int numberOfMusketeersResults = musketeersSearchResults.size();
find.search(termTwo);
List<String> dearlyDepartedSearchResults = results.getResultTitles();
int numberOfDearlyDepartedResults = dearlyDepartedSearchResults.size();
find.search(termOne + " AND " + termTwo);
List<String> andResults = results.getResultTitles();
int numberOfAndResults = andResults.size();
assertThat(numberOfMusketeersResults,greaterThanOrEqualTo(numberOfAndResults));
assertThat(numberOfDearlyDepartedResults, greaterThanOrEqualTo(numberOfAndResults));
String[] andResultsArray = andResults.toArray(new String[andResults.size()]);
assertThat(musketeersSearchResults, hasItems(andResultsArray));
assertThat(dearlyDepartedSearchResults, hasItems(andResultsArray));
find.search(termOne + " OR " + termTwo);
List<String> orResults = results.getResultTitles();
Set<String> concatenatedResults = new HashSet<>(ListUtils.union(musketeersSearchResults, dearlyDepartedSearchResults));
assertThat(orResults.size(), is(concatenatedResults.size()));
assertThat(orResults, containsInAnyOrder(concatenatedResults.toArray()));
find.search(termOne + " XOR " + termTwo);
List<String> xorResults = results.getResultTitles();
concatenatedResults.removeAll(andResults);
assertThat(xorResults.size(), is(concatenatedResults.size()));
assertThat(xorResults, containsInAnyOrder(concatenatedResults.toArray()));
find.search(termOne + " NOT " + termTwo);
List<String> notTermTwo = results.getResultTitles();
Set<String> t1NotT2 = new HashSet<>(concatenatedResults);
t1NotT2.removeAll(dearlyDepartedSearchResults);
assertThat(notTermTwo.size(), is(t1NotT2.size()));
assertThat(notTermTwo, containsInAnyOrder(t1NotT2.toArray()));
find.search(termTwo + " NOT " + termOne);
List<String> notTermOne = results.getResultTitles();
Set<String> t2NotT1 = new HashSet<>(concatenatedResults);
t2NotT1.removeAll(musketeersSearchResults);
assertThat(notTermOne.size(), is(t2NotT1.size()));
assertThat(notTermOne, containsInAnyOrder(t2NotT1.toArray()));
}
//DUPLICATE SEARCH TEST (almost)
@Test
public void testCorrectErrorMessageDisplayed() {
//TODO: map error messages to application type
List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR");
List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets
for (final String searchTerm : boolOperators) {
find.search(searchTerm);
verifyThat("Correct error message for searchterm: " + searchTerm, find.getText(), containsString(Errors.Search.OPERATORS));
}
for (final String searchTerm : stopWords) {
find.search(searchTerm);
verifyThat("Correct error message for searchterm: " + searchTerm, find.getText(), containsString(Errors.Search.STOPWORDS));
}
}
//DUPLICATE SEARCH TEST
@Test
public void testAllowSearchOfStringsThatContainBooleansWithinThem() {
final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED");
for (final String hiddenBooleansProximity : hiddenBooleansProximities) {
find.search(hiddenBooleansProximity);
Waits.loadOrFadeWait();
assertThat(find.getText(), not(containsString(Errors.Search.GENERAL)));
}
}
//DUPLICATE
@Test
public void testSearchParentheses() {
List<String> testSearchTerms = Arrays.asList("(",")",") (",")war"); //"()" appears to be fine
for(String searchTerm : testSearchTerms){
find.search(searchTerm);
assertThat(results, containsText(Errors.Search.OPERATORS));
}
}
//DUPLICATE
@Test
@KnownBug({"IOD-8454","CCUK-3634"})
public void testSearchQuotationMarks() {
List<String> testSearchTerms = Arrays.asList("\"","","\"word","\" word","\" wo\"rd\""); //"\"\"" seems okay and " "
for (String searchTerm : testSearchTerms){
find.search(searchTerm);
Waits.loadOrFadeWait();
assertThat(results, containsText(Errors.Search.QUOTES));
}
}
//DUPLICATE
@Test
public void testWhitespaceSearch() {
find.search(" ");
assertThat(results, containsText(Errors.Search.STOPWORDS));
}
@Test
@KnownBug("CSA-1577")
public void testClickingCustomDateFilterDoesNotRefreshResults(){
find.search("O Captain! My Captain!");
// may not happen the first time
for (int unused = 0; unused < 5; unused++) {
results.toggleDateSelection(FindResultsPage.DateEnum.CUSTOM);
assertThat(results.resultsDiv().getText(), not(containsString("Loading")));
}
}
@Test
@KnownBug("CSA-1665")
public void testSearchTermInResults(){
String searchTerm = "Tiger";
find.search(searchTerm);
for(WebElement searchElement : getDriver().findElements(By.xpath("//*[not(self::h4) and contains(text(),'" + searchTerm + "')]"))){
if(searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(searchElement.getText(), containsString(searchTerm));
}
verifyThat(searchElement, not(hasTagName("a")));
verifyThat(searchElement, hasClass("search-text"));
}
}
// TODO: testMultiWordSearchTermInResults
@Test
public void testRelatedConceptsInResults(){
find.search("Tiger");
for(WebElement relatedConceptLink : results.relatedConcepts()){
String relatedConcept = relatedConceptLink.getText();
for (WebElement relatedConceptElement : getDriver().findElements(By.xpath("//*[contains(@class,'middle-container')]//*[not(self::h4) and contains(text(),'" + relatedConcept + "')]"))) {
if (relatedConceptElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(relatedConceptElement.getText(), containsString(relatedConcept));
}
verifyThat(relatedConceptElement, hasTagName("a"));
verifyThat(relatedConceptElement, hasClass("clickable"));
}
}
}
@Test
public void testSimilarDocumentsShowUp(){
find.search("Doe");
for (WebElement similarResultLink : Lists.reverse(results.similarResultLinks())) {
similarResultLink.click();
WebElement popover = results.popover();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElement(popover, "Loading")));
assertThat(popover.findElement(By.tagName("p")).getText(), not("An error occurred fetching similar documents"));
for(WebElement similarResult : popover.findElements(By.tagName("li"))){
assertThat(similarResult.findElement(By.tagName("a")).getText(), not(isEmptyString()));
assertThat(similarResult.findElement(By.tagName("p")).getText(), not(isEmptyString()));
}
}
}
@Test
@KnownBug("CSA-1630")
public void testAllPromotedDocumentsHaveTitles(){
searchWindow.activate();
PromotionService promotionService = getApplication().promotionService();
try {
promotionService.setUpPromotion(new SpotlightPromotion(Promotion.SpotlightType.HOTWIRE, "Tiger"), "scg-2", 10);
findWindow.activate();
find.search("Tiger");
for(String title : results.getPromotionsTitles()){
assertThat(title, is(not("")));
}
} finally {
searchWindow.activate();
promotionService.deleteAll();
}
}
@Test
@KnownBug("CSA-1763")
public void testPublicIndexesNotSelectedByDefault(){
find.search("Marina and the Diamonds");
verifyThat(find.getSelectedPublicIndexes().size(), is(0));
}
@Test
@KnownBug("CSA-2082")
public void testAutoScroll(){
find.search("my very easy method just speeds up naming ");
verifyThat(results.getResults().size(), lessThanOrEqualTo(30));
scrollToBottom();
verifyThat(results.getResults().size(), allOf(greaterThanOrEqualTo(30), lessThanOrEqualTo(60)));
scrollToBottom();
verifyThat(results.getResults().size(), allOf(greaterThanOrEqualTo(60), lessThanOrEqualTo(90)));
List<String> titles = results.getResultTitles();
Set<String> titlesSet = new HashSet<>(titles);
verifyThat("No duplicate titles", titles.size(), is(titlesSet.size()));
}
@Test
public void testViewportSearchResultNumbers(){
find.search("Messi");
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(30);
scrollToBottom();
results.getResult(31).title().click();
verifyDocViewerTotalDocuments(60);
scrollToBottom();
results.getResult(61).title().click();
verifyDocViewerTotalDocuments(90);
}
@Test
@KnownBug("CCUK-3647")
public void testLessThan30ResultsDoesntAttemptToLoadMore() {
find.search("roland garros");
find.filterBy(new IndexFilter("fifa"));
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(lessThanOrEqualTo(30));
scrollToBottom();
verifyThat(results.resultsDiv(), not(containsText("results found")));
}
@Test
public void testBetween30And60Results(){
find.search("idol");
find.filterBy(new IndexFilter("sitesearch"));
scrollToBottom();
results.getResult(1).title().click();
verifyDocViewerTotalDocuments(lessThanOrEqualTo(60));
verifyThat(results.resultsDiv(), containsText("No more results found"));
}
@Test
public void testNoResults(){
find.search("thissearchwillalmostcertainlyreturnnoresults");
verifyThat(results.resultsDiv(), containsText("No results found"));
}
private void scrollToBottom() {
for(int i = 0; i < 10; i++){
new Actions(getDriver()).sendKeys(Keys.PAGE_DOWN).perform();
}
results.waitForSearchLoadIndicatorToDisappear(FindResultsPage.Container.MIDDLE);
}
private void verifyDocViewerTotalDocuments(int docs){
verifyDocViewerTotalDocuments(is(docs));
}
private void verifyDocViewerTotalDocuments(Matcher matcher){
DocumentViewer docViewer = DocumentViewer.make(getDriver());
verifyThat(docViewer.getTotalDocumentsNumber(), matcher);
docViewer.close();
}
private enum FileType {
HTML("TEXT/HTML","html"),
PDF("APPLICATION/PDF","pdf"),
PLAIN("TEXT/PLAIN","file");
private final String sidebarString;
private final String fileIconString;
FileType(String sidebarString, String fileIconString){
this.sidebarString = sidebarString;
this.fileIconString = fileIconString;
}
public String getFileIconString() {
return fileIconString;
}
public String getSidebarString() {
return sidebarString;
}
}
}
| Review update to testNoResults - now ensures only one error message
| integration-tests-hosted/src/test/java/com/autonomy/abc/find/FindITCase.java | Review update to testNoResults - now ensures only one error message | <ide><path>ntegration-tests-hosted/src/test/java/com/autonomy/abc/find/FindITCase.java
<ide> import org.openqa.selenium.support.ui.WebDriverWait;
<ide>
<ide> import java.util.*;
<add>import java.util.regex.Pattern;
<ide>
<ide> import static com.autonomy.abc.framework.ABCAssert.assertThat;
<ide> import static com.autonomy.abc.framework.ABCAssert.verifyThat;
<ide> @Test
<ide> public void testNoResults(){
<ide> find.search("thissearchwillalmostcertainlyreturnnoresults");
<del>
<ide> verifyThat(results.resultsDiv(), containsText("No results found"));
<add>
<add> scrollToBottom();
<add> int i = 0;
<add> Pattern p = Pattern.compile("results found");
<add> java.util.regex.Matcher m = p.matcher(results.resultsDiv().getText());
<add>
<add> while(m.find()){
<add> i++;
<add> }
<add>
<add> verifyThat("Only one message showing at the bottom of search results", i, is(1));
<ide> }
<ide>
<ide> private void scrollToBottom() { |
|
Java | apache-2.0 | 3b7fa1eb4ea436115d5d60b1d71ca39768b0a456 | 0 | billho/symphony,billho/symphony,billho/symphony | /*
* Symphony - A modern community (forum/BBS/SNS/blog) platform written in Java.
* Copyright (C) 2012-2018, b3log.org & hacpai.com
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.b3log.symphony.event;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.event.AbstractEventListener;
import org.b3log.latke.event.Event;
import org.b3log.latke.event.EventException;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.ioc.inject.Named;
import org.b3log.latke.ioc.inject.Singleton;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.symphony.model.*;
import org.b3log.symphony.service.FollowQueryService;
import org.b3log.symphony.service.NotificationMgmtService;
import org.b3log.symphony.service.RoleQueryService;
import org.b3log.symphony.service.UserQueryService;
import org.b3log.symphony.util.Escapes;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Sends article add related notifications.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.3.4.16, Aug 6, 2018
* @since 0.2.0
*/
@Named
@Singleton
public class ArticleAddNotifier extends AbstractEventListener<JSONObject> {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(ArticleAddNotifier.class);
/**
* Notification management service.
*/
@Inject
private NotificationMgmtService notificationMgmtService;
/**
* Follow query service.
*/
@Inject
private FollowQueryService followQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Role query service.
*/
@Inject
private RoleQueryService roleQueryService;
@Override
public void action(final Event<JSONObject> event) throws EventException {
final JSONObject data = event.getData();
LOGGER.log(Level.TRACE, "Processing an event [type={0}, data={1}]", event.getType(), data);
try {
final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
final String articleId = originalArticle.optString(Keys.OBJECT_ID);
final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
final Set<String> requisiteAtUserPermissions = new HashSet<>();
requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER);
final boolean hasAtUserPerm = roleQueryService.userHasPermissions(articleAuthorId, requisiteAtUserPermissions);
final Set<String> atedUserIds = new HashSet<>();
if (hasAtUserPerm) {
// 'At' Notification
final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
final Set<String> atUserNames = userQueryService.getUserNames(articleContent);
atUserNames.remove(articleAuthorName); // Do not notify the author itself
for (final String userName : atUserNames) {
final JSONObject user = userQueryService.getUserByName(userName);
if (null == user) {
LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);
continue;
}
final JSONObject requestJSONObject = new JSONObject();
final String atedUserId = user.optString(Keys.OBJECT_ID);
requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId);
requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addAtNotification(requestJSONObject);
atedUserIds.add(atedUserId);
}
}
final String tags = originalArticle.optString(Article.ARTICLE_TAGS);
// 'following - user' Notification
if (Article.ARTICLE_TYPE_C_DISCUSSION != originalArticle.optInt(Article.ARTICLE_TYPE)
&& Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)
&& !Tag.TAG_TITLE_C_SANDBOX.equals(tags)
&& !StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) {
final JSONObject followerUsersResult = followQueryService.getFollowerUsers(
UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleAuthorId, 1, Integer.MAX_VALUE);
final List<JSONObject> followerUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS);
for (final JSONObject followerUser : followerUsers) {
final JSONObject requestJSONObject = new JSONObject();
final String followerUserId = followerUser.optString(Keys.OBJECT_ID);
if (atedUserIds.contains(followerUserId)) {
continue;
}
requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId);
requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addFollowingUserNotification(requestJSONObject);
}
}
final String articleTitle = Escapes.escapeHTML(originalArticle.optString(Article.ARTICLE_TITLE));
// 'Broadcast' Notification
if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)
&& Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)) {
final String city = originalArticle.optString(Article.ARTICLE_CITY);
if (StringUtils.isNotBlank(city)) {
final JSONObject requestJSONObject = new JSONObject();
requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1);
requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE);
requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE);
final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime();
requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime);
requestJSONObject.put(UserExt.USER_CITY, city);
final JSONObject result = userQueryService.getUsersByCity(requestJSONObject);
final JSONArray users = result.optJSONArray(User.USERS);
for (int i = 0; i < users.length(); i++) {
final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID);
if (userId.equals(articleAuthorId)) {
continue;
}
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, userId);
notification.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addBroadcastNotification(notification);
}
LOGGER.info("City [" + city + "] broadcast [users=" + users.length() + "]");
}
}
// 'Sys Announce' Notification
if (StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) {
final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime();
final JSONObject result = userQueryService.getLatestLoggedInUsers(
latestLoginTime, 1, Integer.MAX_VALUE, Integer.MAX_VALUE);
final JSONArray users = result.optJSONArray(User.USERS);
for (int i = 0; i < users.length(); i++) {
final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID);
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, userId);
notification.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addSysAnnounceArticleNotification(notification);
}
LOGGER.info("System announcement [" + articleTitle + "] broadcast [users=" + users.length() + "]");
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Sends the article add notification failed", e);
}
}
/**
* Gets the event type {@linkplain EventTypes#ADD_ARTICLE}.
*
* @return event type
*/
@Override
public String getEventType() {
return EventTypes.ADD_ARTICLE;
}
}
| src/main/java/org/b3log/symphony/event/ArticleAddNotifier.java | /*
* Symphony - A modern community (forum/BBS/SNS/blog) platform written in Java.
* Copyright (C) 2012-2018, b3log.org & hacpai.com
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.b3log.symphony.event;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.event.AbstractEventListener;
import org.b3log.latke.event.Event;
import org.b3log.latke.event.EventException;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.ioc.inject.Named;
import org.b3log.latke.ioc.inject.Singleton;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.symphony.model.*;
import org.b3log.symphony.service.FollowQueryService;
import org.b3log.symphony.service.NotificationMgmtService;
import org.b3log.symphony.service.RoleQueryService;
import org.b3log.symphony.service.UserQueryService;
import org.b3log.symphony.util.Escapes;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Sends article add related notifications.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.3.4.15, Jun 6, 2018
* @since 0.2.0
*/
@Named
@Singleton
public class ArticleAddNotifier extends AbstractEventListener<JSONObject> {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(ArticleAddNotifier.class);
/**
* Notification management service.
*/
@Inject
private NotificationMgmtService notificationMgmtService;
/**
* Follow query service.
*/
@Inject
private FollowQueryService followQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Role query service.
*/
@Inject
private RoleQueryService roleQueryService;
@Override
public void action(final Event<JSONObject> event) throws EventException {
final JSONObject data = event.getData();
LOGGER.log(Level.TRACE, "Processing an event [type={0}, data={1}]", event.getType(), data);
try {
final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
final String articleId = originalArticle.optString(Keys.OBJECT_ID);
final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
final Set<String> requisiteAtUserPermissions = new HashSet<>();
requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER);
final boolean hasAtUserPerm = roleQueryService.userHasPermissions(articleAuthorId, requisiteAtUserPermissions);
final Set<String> atedUserIds = new HashSet<>();
if (hasAtUserPerm) {
// 'At' Notification
final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
final Set<String> atUserNames = userQueryService.getUserNames(articleContent);
atUserNames.remove(articleAuthorName); // Do not notify the author itself
for (final String userName : atUserNames) {
final JSONObject user = userQueryService.getUserByName(userName);
if (null == user) {
LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);
continue;
}
final JSONObject requestJSONObject = new JSONObject();
final String atedUserId = user.optString(Keys.OBJECT_ID);
requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId);
requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addAtNotification(requestJSONObject);
atedUserIds.add(atedUserId);
}
}
final String tags = originalArticle.optString(Article.ARTICLE_TAGS);
// 'following - user' Notification
if (Article.ARTICLE_TYPE_C_DISCUSSION != originalArticle.optInt(Article.ARTICLE_TYPE)
&& Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)
&& !Tag.TAG_TITLE_C_SANDBOX.equals(tags)
&& !StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) {
final JSONObject followerUsersResult = followQueryService.getFollowerUsers(
UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleAuthorId, 1, Integer.MAX_VALUE);
final List<JSONObject> followerUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS);
for (final JSONObject followerUser : followerUsers) {
final JSONObject requestJSONObject = new JSONObject();
final String followerUserId = followerUser.optString(Keys.OBJECT_ID);
if (atedUserIds.contains(followerUserId)) {
continue;
}
requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId);
requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addFollowingUserNotification(requestJSONObject);
}
}
final String articleTitle = Escapes.escapeHTML(originalArticle.optString(Article.ARTICLE_TITLE));
// 'Broadcast' Notification
if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)) {
final String city = originalArticle.optString(Article.ARTICLE_CITY);
if (StringUtils.isNotBlank(city)) {
final JSONObject requestJSONObject = new JSONObject();
requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1);
requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE);
requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE);
final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime();
requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime);
requestJSONObject.put(UserExt.USER_CITY, city);
final JSONObject result = userQueryService.getUsersByCity(requestJSONObject);
final JSONArray users = result.optJSONArray(User.USERS);
for (int i = 0; i < users.length(); i++) {
final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID);
if (userId.equals(articleAuthorId)) {
continue;
}
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, userId);
notification.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addBroadcastNotification(notification);
}
LOGGER.info("City [" + city + "] broadcast [users=" + users.length() + "]");
}
}
// 'Sys Announce' Notification
if (StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) {
final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime();
final JSONObject result = userQueryService.getLatestLoggedInUsers(
latestLoginTime, 1, Integer.MAX_VALUE, Integer.MAX_VALUE);
final JSONArray users = result.optJSONArray(User.USERS);
for (int i = 0; i < users.length(); i++) {
final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID);
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, userId);
notification.put(Notification.NOTIFICATION_DATA_ID, articleId);
notificationMgmtService.addSysAnnounceArticleNotification(notification);
}
LOGGER.info("System announcement [" + articleTitle + "] broadcast [users=" + users.length() + "]");
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Sends the article add notification failed", e);
}
}
/**
* Gets the event type {@linkplain EventTypes#ADD_ARTICLE}.
*
* @return event type
*/
@Override
public String getEventType() {
return EventTypes.ADD_ARTICLE;
}
}
| :lock: 修复同城使用匿名漏洞
| src/main/java/org/b3log/symphony/event/ArticleAddNotifier.java | :lock: 修复同城使用匿名漏洞 | <ide><path>rc/main/java/org/b3log/symphony/event/ArticleAddNotifier.java
<ide> * Sends article add related notifications.
<ide> *
<ide> * @author <a href="http://88250.b3log.org">Liang Ding</a>
<del> * @version 1.3.4.15, Jun 6, 2018
<add> * @version 1.3.4.16, Aug 6, 2018
<ide> * @since 0.2.0
<ide> */
<ide> @Named
<ide> final String articleTitle = Escapes.escapeHTML(originalArticle.optString(Article.ARTICLE_TITLE));
<ide>
<ide> // 'Broadcast' Notification
<del> if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)) {
<add> if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)
<add> && Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)) {
<ide> final String city = originalArticle.optString(Article.ARTICLE_CITY);
<ide>
<ide> if (StringUtils.isNotBlank(city)) { |
|
Java | apache-2.0 | a0bf7d4c38536740bd267d2e24f229e1955b2ffb | 0 | serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ext.postgresql.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBPQualifiedObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.IPropertyCacheValidator;
import org.jkiss.dbeaver.model.meta.LazyProperty;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.meta.PropertyGroup;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSEntityType;
import org.jkiss.dbeaver.model.struct.rdb.DBSSequence;
import org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex;
import org.jkiss.utils.CommonUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* PostgreSequence
*/
public class PostgreSequence extends PostgreTableBase implements DBSSequence, DBPQualifiedObject
{
private static final Log log = Log.getLog(PostgreSequence.class);
public static class AdditionalInfo {
private volatile boolean loaded = false;
private Number lastValue;
private Number minValue;
private Number maxValue;
private Number incrementBy;
private Number cacheValue;
private boolean isCycled;
@Property(viewable = true, editable = true, updatable = false, order = 10)
public Number getLastValue() {
return lastValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 11)
public Number getMinValue() {
return minValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 12)
public Number getMaxValue() {
return maxValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 13)
public Number getIncrementBy() {
return incrementBy;
}
@Property(viewable = true, editable = true, updatable = false, order = 14)
public Number getCacheValue() {
return cacheValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 15)
public boolean isCycled() {
return isCycled;
}
}
public static class AdditionalInfoValidator implements IPropertyCacheValidator<PostgreSequence> {
@Override
public boolean isPropertyCached(PostgreSequence object, Object propertyId)
{
return object.additionalInfo.loaded;
}
}
private final AdditionalInfo additionalInfo = new AdditionalInfo();
public PostgreSequence(PostgreSchema schema, JDBCResultSet dbResult) {
super(schema, dbResult);
}
public PostgreSequence(PostgreSchema catalog) {
super(catalog);
}
@PropertyGroup()
@LazyProperty(cacheValidator = AdditionalInfoValidator.class)
public AdditionalInfo getAdditionalInfo(DBRProgressMonitor monitor) throws DBCException
{
synchronized (additionalInfo) {
if (!additionalInfo.loaded) {
loadAdditionalInfo(monitor);
}
return additionalInfo;
}
}
private void loadAdditionalInfo(DBRProgressMonitor monitor) {
try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load sequence additional info")) {
if (getDataSource().isServerVersionAtLeast(10, 0)) {
try (JDBCPreparedStatement dbSeqStat = session.prepareStatement(
"SELECT * from pg_catalog.pg_sequences WHERE schemaname=? AND sequencename=?")) {
dbSeqStat.setString(1, getSchema().getName());
dbSeqStat.setString(2, getName());
try (JDBCResultSet seqResults = dbSeqStat.executeQuery()) {
if (seqResults.next()) {
additionalInfo.lastValue = JDBCUtils.safeGetLong(seqResults, "last_value");
additionalInfo.minValue = JDBCUtils.safeGetLong(seqResults, "min_value");
additionalInfo.maxValue = JDBCUtils.safeGetLong(seqResults, "max_value");
additionalInfo.incrementBy = JDBCUtils.safeGetLong(seqResults, "increment_by");
additionalInfo.cacheValue = JDBCUtils.safeGetLong(seqResults, "cache_size");
additionalInfo.isCycled = JDBCUtils.safeGetBoolean(seqResults, "cycle");
}
}
}
} else {
try (JDBCPreparedStatement dbSeqStat = session.prepareStatement(
"SELECT * from " + getFullyQualifiedName(DBPEvaluationContext.DML))) {
try (JDBCResultSet seqResults = dbSeqStat.executeQuery()) {
if (seqResults.next()) {
additionalInfo.lastValue = JDBCUtils.safeGetLong(seqResults, "last_value");
additionalInfo.minValue = JDBCUtils.safeGetLong(seqResults, "min_value");
additionalInfo.maxValue = JDBCUtils.safeGetLong(seqResults, "max_value");
additionalInfo.incrementBy = JDBCUtils.safeGetLong(seqResults, "increment_by");
additionalInfo.cacheValue = JDBCUtils.safeGetLong(seqResults, "cache_size");
additionalInfo.isCycled = JDBCUtils.safeGetBoolean(seqResults, "is_cycled");
}
}
}
}
additionalInfo.loaded = true;
} catch (Exception e) {
log.warn("Error reading sequence values", e);
}
}
@Override
public Number getLastValue() {
return additionalInfo.lastValue;
}
@Override
public Number getMinValue() {
return additionalInfo.minValue;
}
@Override
public Number getMaxValue() {
return additionalInfo.maxValue;
}
@Override
public Number getIncrementBy() {
return additionalInfo.incrementBy;
}
///////////////////////////////////////////////////////////////////////
// Entity
@NotNull
@Override
public DBSEntityType getEntityType() {
return DBSEntityType.SEQUENCE;
}
@Override
public boolean isView() {
return false;
}
@Override
public Collection<? extends DBSTableIndex> getIndexes(DBRProgressMonitor monitor) throws DBException {
return null;
}
@Override
public void setObjectDefinitionText(String sourceText) throws DBException {
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor, Map<String, Object> options) throws DBException {
AdditionalInfo info = getAdditionalInfo(monitor);
StringBuilder sql = new StringBuilder();
sql.append("-- DROP SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)).append(";\n\n");
sql.append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL));
if (info.getIncrementBy() != null && info.getIncrementBy().longValue() > 0) {
sql.append("\n\tINCREMENT BY ").append(info.getIncrementBy());
}
if (info.getMinValue() != null && info.getMinValue().longValue() > 0) {
sql.append("\n\tMINVALUE ").append(info.getMinValue());
} else {
sql.append("\n\tNO MINVALUE");
}
if (info.getMaxValue() != null && info.getMaxValue().longValue() > 0) {
sql.append("\n\tMAXVALUE ").append(info.getMaxValue());
} else {
sql.append("\n\tNO MAXVALUE");
}
if (info.getLastValue() != null && info.getLastValue().longValue() > 0) {
sql.append("\n\tSTART ").append(info.getLastValue());
}
if (info.getCacheValue() != null && info.getCacheValue().longValue() > 0) {
sql.append("\n\tCACHE ").append(info.getCacheValue())
.append("\n\t").append(info.isCycled ? "" : "NO ").append("CYCLE")
.append(";");
}
if (!CommonUtils.isEmpty(getDescription())) {
sql.append("\nCOMMENT ON SEQUENCE ").append(DBUtils.getQuotedIdentifier(this)).append(" IS ")
.append(SQLUtils.quoteString(this, getDescription())).append(";");
}
List<DBEPersistAction> actions = new ArrayList<>();
PostgreUtils.getObjectGrantPermissionActions(monitor, this, actions, options);
if (!actions.isEmpty()) {
sql.append("\n\n");
sql.append(SQLUtils.generateScript(getDataSource(), actions.toArray(new DBEPersistAction[actions.size()]), false));
}
return sql.toString();
}
public String generateChangeOwnerQuery(String owner) {
return "ALTER SEQUENCE " + DBUtils.getObjectFullName(this, DBPEvaluationContext.DDL) + " OWNER TO " + owner;
}
}
| plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ext.postgresql.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBPQualifiedObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.IPropertyCacheValidator;
import org.jkiss.dbeaver.model.meta.LazyProperty;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.meta.PropertyGroup;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSEntityType;
import org.jkiss.dbeaver.model.struct.rdb.DBSSequence;
import org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex;
import org.jkiss.utils.CommonUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* PostgreSequence
*/
public class PostgreSequence extends PostgreTableBase implements DBSSequence, DBPQualifiedObject
{
private static final Log log = Log.getLog(PostgreSequence.class);
public static class AdditionalInfo {
private volatile boolean loaded = false;
private Number lastValue;
private Number minValue;
private Number maxValue;
private Number incrementBy;
private Number cacheValue;
private boolean isCycled;
@Property(viewable = true, editable = true, updatable = false, order = 10)
public Number getLastValue() {
return lastValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 11)
public Number getMinValue() {
return minValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 12)
public Number getMaxValue() {
return maxValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 13)
public Number getIncrementBy() {
return incrementBy;
}
@Property(viewable = true, editable = true, updatable = false, order = 14)
public Number getCacheValue() {
return cacheValue;
}
@Property(viewable = true, editable = true, updatable = false, order = 15)
public boolean isCycled() {
return isCycled;
}
}
public static class AdditionalInfoValidator implements IPropertyCacheValidator<PostgreSequence> {
@Override
public boolean isPropertyCached(PostgreSequence object, Object propertyId)
{
return object.additionalInfo.loaded;
}
}
private final AdditionalInfo additionalInfo = new AdditionalInfo();
public PostgreSequence(PostgreSchema schema, JDBCResultSet dbResult) {
super(schema, dbResult);
}
public PostgreSequence(PostgreSchema catalog) {
super(catalog);
}
@PropertyGroup()
@LazyProperty(cacheValidator = AdditionalInfoValidator.class)
public AdditionalInfo getAdditionalInfo(DBRProgressMonitor monitor) throws DBCException
{
synchronized (additionalInfo) {
if (!additionalInfo.loaded) {
loadAdditionalInfo(monitor);
}
return additionalInfo;
}
}
private void loadAdditionalInfo(DBRProgressMonitor monitor) {
try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load sequence additional info")) {
if (getDataSource().isServerVersionAtLeast(10, 0)) {
try (JDBCPreparedStatement dbSeqStat = session.prepareStatement(
"SELECT * from pg_catalog.pg_sequences WHERE schemaname=? AND sequencename=?")) {
dbSeqStat.setString(1, getSchema().getName());
dbSeqStat.setString(2, getName());
try (JDBCResultSet seqResults = dbSeqStat.executeQuery()) {
if (seqResults.next()) {
additionalInfo.lastValue = JDBCUtils.safeGetLong(seqResults, "last_value");
additionalInfo.minValue = JDBCUtils.safeGetLong(seqResults, "min_value");
additionalInfo.maxValue = JDBCUtils.safeGetLong(seqResults, "max_value");
additionalInfo.incrementBy = JDBCUtils.safeGetLong(seqResults, "increment_by");
additionalInfo.cacheValue = JDBCUtils.safeGetLong(seqResults, "cache_size");
additionalInfo.isCycled = JDBCUtils.safeGetBoolean(seqResults, "cycle");
}
}
}
} else {
try (JDBCPreparedStatement dbSeqStat = session.prepareStatement(
"SELECT * from " + getFullyQualifiedName(DBPEvaluationContext.DML))) {
try (JDBCResultSet seqResults = dbSeqStat.executeQuery()) {
if (seqResults.next()) {
additionalInfo.lastValue = JDBCUtils.safeGetLong(seqResults, "last_value");
additionalInfo.minValue = JDBCUtils.safeGetLong(seqResults, "min_value");
additionalInfo.maxValue = JDBCUtils.safeGetLong(seqResults, "max_value");
additionalInfo.incrementBy = JDBCUtils.safeGetLong(seqResults, "increment_by");
additionalInfo.cacheValue = JDBCUtils.safeGetLong(seqResults, "cache_size");
additionalInfo.isCycled = JDBCUtils.safeGetBoolean(seqResults, "is_cycled");
}
}
}
}
additionalInfo.loaded = true;
} catch (Exception e) {
log.warn("Error reading sequence values", e);
}
}
@Override
public Number getLastValue() {
return additionalInfo.lastValue;
}
@Override
public Number getMinValue() {
return additionalInfo.minValue;
}
@Override
public Number getMaxValue() {
return additionalInfo.maxValue;
}
@Override
public Number getIncrementBy() {
return additionalInfo.incrementBy;
}
///////////////////////////////////////////////////////////////////////
// Entity
@NotNull
@Override
public DBSEntityType getEntityType() {
return DBSEntityType.SEQUENCE;
}
@Override
public boolean isView() {
return false;
}
@Override
public Collection<? extends DBSTableIndex> getIndexes(DBRProgressMonitor monitor) throws DBException {
return null;
}
@Override
public void setObjectDefinitionText(String sourceText) throws DBException {
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor, Map<String, Object> options) throws DBException {
AdditionalInfo info = getAdditionalInfo(monitor);
StringBuilder sql = new StringBuilder();
sql.append("-- DROP SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)).append(";\n\n");
sql.append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL));
if (info.getIncrementBy() != null && info.getIncrementBy().longValue() > 0) {
sql.append("\n\tINCREMENT BY ").append(info.getIncrementBy());
}
if (info.getMinValue() != null && info.getMinValue().longValue() > 0) {
sql.append("\n\tMINVALUE ").append(info.getMinValue());
} else {
sql.append("\n\tNO MINVALUE");
}
if (info.getMaxValue() != null && info.getMaxValue().longValue() > 0) {
sql.append("\n\tMAXVALUE ").append(info.getMaxValue());
} else {
sql.append("\n\tNO MAXVALUE");
}
if (info.getLastValue() != null && info.getLastValue().longValue() > 0) {
sql.append("\n\tSTART ").append(info.getLastValue());
}
sql.append("\n\tCACHE ").append(info.getCacheValue())
.append("\n\t").append(info.isCycled ? "" : "NO ").append("CYCLE")
.append(";");
if (!CommonUtils.isEmpty(getDescription())) {
sql.append("\nCOMMENT ON SEQUENCE ").append(DBUtils.getQuotedIdentifier(this)).append(" IS ")
.append(SQLUtils.quoteString(this, getDescription())).append(";");
}
List<DBEPersistAction> actions = new ArrayList<>();
PostgreUtils.getObjectGrantPermissionActions(monitor, this, actions, options);
if (!actions.isEmpty()) {
sql.append("\n\n");
sql.append(SQLUtils.generateScript(getDataSource(), actions.toArray(new DBEPersistAction[actions.size()]), false));
}
return sql.toString();
}
public String generateChangeOwnerQuery(String owner) {
return "ALTER SEQUENCE " + DBUtils.getObjectFullName(this, DBPEvaluationContext.DDL) + " OWNER TO " + owner;
}
}
| #5156 PG: sequence DDL gen fix
Former-commit-id: b563a1de21e7203e893f5b37fe29f579e7d68bce | plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java | #5156 PG: sequence DDL gen fix | <ide><path>lugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java
<ide> if (info.getLastValue() != null && info.getLastValue().longValue() > 0) {
<ide> sql.append("\n\tSTART ").append(info.getLastValue());
<ide> }
<del> sql.append("\n\tCACHE ").append(info.getCacheValue())
<del> .append("\n\t").append(info.isCycled ? "" : "NO ").append("CYCLE")
<del> .append(";");
<add> if (info.getCacheValue() != null && info.getCacheValue().longValue() > 0) {
<add> sql.append("\n\tCACHE ").append(info.getCacheValue())
<add> .append("\n\t").append(info.isCycled ? "" : "NO ").append("CYCLE")
<add> .append(";");
<add> }
<ide>
<ide> if (!CommonUtils.isEmpty(getDescription())) {
<ide> sql.append("\nCOMMENT ON SEQUENCE ").append(DBUtils.getQuotedIdentifier(this)).append(" IS ") |
|
Java | bsd-3-clause | 8042182efc71e48c0e7e04a7a9a7399bf8f02b5e | 0 | dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk | /*
* Copyright (c) 2017, 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.
*/
package org.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.handlers.IdentifiableSyncHandlerImpl;
import org.hisp.dhis.android.core.arch.handlers.SyncHandler;
import org.hisp.dhis.android.core.arch.handlers.SyncHandlerWithTransformer;
import org.hisp.dhis.android.core.common.HandleAction;
import org.hisp.dhis.android.core.common.IdentifiableObjectStore;
import org.hisp.dhis.android.core.common.ObjectStyle;
import org.hisp.dhis.android.core.common.ObjectStyleHandler;
import org.hisp.dhis.android.core.common.ObjectStyleModelBuilder;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
public final class TrackedEntityTypeHandler extends IdentifiableSyncHandlerImpl<TrackedEntityType> {
private final SyncHandlerWithTransformer<ObjectStyle> styleHandler;
private TrackedEntityTypeHandler(IdentifiableObjectStore<TrackedEntityType> trackedEntityTypeStore,
SyncHandlerWithTransformer<ObjectStyle> styleHandler) {
super(trackedEntityTypeStore);
this.styleHandler = styleHandler;
}
@Override
protected void afterObjectHandled(TrackedEntityType trackedEntityType, HandleAction action) {
styleHandler.handle(trackedEntityType.style(), new ObjectStyleModelBuilder(trackedEntityType.uid(),
TrackedEntityTypeTableInfo.TABLE_INFO.name()));
}
public static SyncHandler<TrackedEntityType> create(DatabaseAdapter databaseAdapter) {
return new TrackedEntityTypeHandler(
TrackedEntityTypeStore.create(databaseAdapter),
ObjectStyleHandler.create(databaseAdapter));
}
} | core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityTypeHandler.java | /*
* Copyright (c) 2017, 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.
*/
package org.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.handlers.SyncHandlerWithTransformer;
import org.hisp.dhis.android.core.common.GenericHandler;
import org.hisp.dhis.android.core.common.HandleAction;
import org.hisp.dhis.android.core.common.IdentifiableHandlerImpl;
import org.hisp.dhis.android.core.common.IdentifiableObjectStore;
import org.hisp.dhis.android.core.common.ObjectStyle;
import org.hisp.dhis.android.core.common.ObjectStyleHandler;
import org.hisp.dhis.android.core.common.ObjectStyleModelBuilder;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
public final class TrackedEntityTypeHandler extends IdentifiableHandlerImpl<TrackedEntityType, TrackedEntityTypeModel> {
private final SyncHandlerWithTransformer<ObjectStyle> styleHandler;
private TrackedEntityTypeHandler(IdentifiableObjectStore<TrackedEntityTypeModel> trackedEntityTypeStore,
SyncHandlerWithTransformer<ObjectStyle> styleHandler) {
super(trackedEntityTypeStore);
this.styleHandler = styleHandler;
}
@Override
protected void afterObjectHandled(TrackedEntityType trackedEntityType, HandleAction action) {
styleHandler.handle(trackedEntityType.style(), new ObjectStyleModelBuilder(trackedEntityType.uid(),
TrackedEntityTypeModel.TABLE));
}
public static GenericHandler<TrackedEntityType, TrackedEntityTypeModel> create(DatabaseAdapter databaseAdapter) {
return new TrackedEntityTypeHandler(
TrackedEntityTypeStore.create(databaseAdapter),
ObjectStyleHandler.create(databaseAdapter));
}
}
| [ANDROSDK-434] Unify TETHandler
| core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityTypeHandler.java | [ANDROSDK-434] Unify TETHandler | <ide><path>ore/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityTypeHandler.java
<ide> */
<ide> package org.hisp.dhis.android.core.trackedentity;
<ide>
<add>import org.hisp.dhis.android.core.arch.handlers.IdentifiableSyncHandlerImpl;
<add>import org.hisp.dhis.android.core.arch.handlers.SyncHandler;
<ide> import org.hisp.dhis.android.core.arch.handlers.SyncHandlerWithTransformer;
<del>import org.hisp.dhis.android.core.common.GenericHandler;
<ide> import org.hisp.dhis.android.core.common.HandleAction;
<del>import org.hisp.dhis.android.core.common.IdentifiableHandlerImpl;
<ide> import org.hisp.dhis.android.core.common.IdentifiableObjectStore;
<ide> import org.hisp.dhis.android.core.common.ObjectStyle;
<ide> import org.hisp.dhis.android.core.common.ObjectStyleHandler;
<ide> import org.hisp.dhis.android.core.common.ObjectStyleModelBuilder;
<ide> import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
<ide>
<del>public final class TrackedEntityTypeHandler extends IdentifiableHandlerImpl<TrackedEntityType, TrackedEntityTypeModel> {
<add>public final class TrackedEntityTypeHandler extends IdentifiableSyncHandlerImpl<TrackedEntityType> {
<add>
<ide> private final SyncHandlerWithTransformer<ObjectStyle> styleHandler;
<ide>
<del> private TrackedEntityTypeHandler(IdentifiableObjectStore<TrackedEntityTypeModel> trackedEntityTypeStore,
<add> private TrackedEntityTypeHandler(IdentifiableObjectStore<TrackedEntityType> trackedEntityTypeStore,
<ide> SyncHandlerWithTransformer<ObjectStyle> styleHandler) {
<ide> super(trackedEntityTypeStore);
<ide> this.styleHandler = styleHandler;
<ide> @Override
<ide> protected void afterObjectHandled(TrackedEntityType trackedEntityType, HandleAction action) {
<ide> styleHandler.handle(trackedEntityType.style(), new ObjectStyleModelBuilder(trackedEntityType.uid(),
<del> TrackedEntityTypeModel.TABLE));
<add> TrackedEntityTypeTableInfo.TABLE_INFO.name()));
<ide> }
<ide>
<del> public static GenericHandler<TrackedEntityType, TrackedEntityTypeModel> create(DatabaseAdapter databaseAdapter) {
<add> public static SyncHandler<TrackedEntityType> create(DatabaseAdapter databaseAdapter) {
<ide> return new TrackedEntityTypeHandler(
<ide> TrackedEntityTypeStore.create(databaseAdapter),
<ide> ObjectStyleHandler.create(databaseAdapter)); |
|
Java | mit | 108918b8999771a743a5625aab6544a0b267172a | 0 | ValentinMinder/wasadigi-Teaching-HEIGVD-RES,ValentinMinder/wasadigi-Teaching-HEIGVD-RES | package ch.heigvd.res.http.test;
import ch.heigvd.res.http.HttpServer;
import ch.heigvd.res.http.interfaces.IHttpServer;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* This test class validates the fact that your server is able to handle
* multiple clients concurrently (because you are running workers on multiple
* threads). To implement the test, your server needs to implement a simple
* "streaming" function. When your server receives requests for a specific url
* (/streaming), it should go over a loop of multiple iterations. At each iteration,
* it should send a line of content and sleep for a specified time. This means that
* it might take several seconds for the server to return the complete response.
* By running multiple clients at the same time and measuring the total time, it
* is possible for the test to check that the requests were handled in parallel and
* not in sequence.
*
* @author Olivier Liechti
*/
public class ConcurrentHttpServerTest extends HttpServerTest {
final static Logger LOG = Logger.getLogger(ConcurrentHttpServerTest.class.getName());
/**
* The HTTP server should be able to handle multiple clients in parallel. To test this
* behavior, we submit 3 requests in 3 different threads and target the "/steaming" URI.
* Read carefully the body of the response, you need to respect that syntax. Note that
* System.currentTimeMillis() has been used when sending the first and last line in the
* body. Notice that there are 3 lines starting with "Here is one part" because the
* query string param "iterations" had a value of 3. Notice that
* 1397669533261-1397669530259 = 3002 (which is a bit more than 3 iterations * 1000 ms
* of sleep time per iteration).
*
* --------------------------------------------------------------------
* The client sends this request (3 iterations, sleep time of 1 second)
* --------------------------------------------------------------------
* HTTP/1.1 200 OK
* Content-type: text/plain
* START
* END
* GET /streaming?iterations=3&sleepTime=1000 HTTP/1.1
* Host: localhost
*
* --------------------------------------------------------------------------------------------------------------------
* The server sends this response (System.currentTimeMillis() called on first line and last line, 1 line per iteration)
* --------------------------------------------------------------------------------------------------------------------
* HTTP/1.1 200 OK
* Connection: close
* Content-type: text/plain
*
* START 1397669530259
* Here is one part of the message: 0
* Here is one part of the message: 1
* Here is one part of the message: 2
* END 1397669533261
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public void theHttpServerShouldHandleConcurrentClients() throws IOException, InterruptedException {
IHttpServer server = new HttpServer(rootDirectory, port);
server.start();
int iterations = 5;
long sleepTime = 500;
long expectedResponseTime = iterations * sleepTime;
// for the test, we accept a difference of 10% between the estimated time
// and the measured time
long margin = expectedResponseTime / 10;
// Your server should detect "streaming" as the target resource. It should extract the value of
// iterations and sleepTime from the query string in the target URI. It should then use these
// values when implementing the generation of the response. It should take a little bit more than
// iterations * sleepTime milliseconds for the server to generate 1 response. It should take a little
// bit more than iterations * sleepTime milliseconds for the server to generate 3 responses.
String url = server.getRootUrl() + "streaming?iterations=" + iterations + "&sleepTime=" + sleepTime;
// We will send the requests in multiple threads
Thread t1 = createClientThread(url);
Thread t2 = createClientThread(url);
Thread t3 = createClientThread(url);
// Let's start the timer and send the requests...
long startTime = System.currentTimeMillis();
t1.start();
t2.start();
t3.start();
// Let's wait for the 3 requests to have been handled by the server and take the time...
t1.join();
t2.join();
t3.join();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
assertTrue(Math.abs(duration - expectedResponseTime) < margin);
server.stop();
}
private Thread createClientThread(final String url) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
long clientStartTime = System.currentTimeMillis();
byte[] response = fetchUrl(url);
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response)));
String firstLine = br.readLine();
String lastLine = null;
String line = br.readLine();
while (line != null) {
lastLine = line;
line = br.readLine();
}
long clientEndTime = System.currentTimeMillis();
long clientDuration = clientEndTime - clientStartTime;
long serverStartTime = Long.parseLong(firstLine.split(" ")[1]);
long serverEndTime = Long.parseLong(lastLine.split(" ")[1]);
long serverDuration = serverEndTime - serverStartTime;
assertTrue(Math.abs(serverDuration - clientDuration) < 1000);
} catch (IOException ex) {
Logger.getLogger(HttpServerTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
return t;
}}
| labs/06-HttpImplementation/HttpLibraryTest/test/ch/heigvd/res/http/test/ConcurrentHttpServerTest.java | package ch.heigvd.res.http.test;
import ch.heigvd.res.http.HttpServer;
import ch.heigvd.res.http.interfaces.IHttpServer;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* This test class validates the fact that your server is able to handle
* multiple clients concurrently (because you are running workers on multiple
* threads). To implement the test, your server needs to implement a simple
* "streaming" function. When your server receives requests for a specific url
* (/streaming), it should go over a loop of multiple iterations. At each iteration,
* it should send a line of content and sleep for a specified time. This means that
* it might take several seconds for the server to return the complete response.
* By running multiple clients at the same time and measuring the total time, it
* is possible for the test to check that the requests were handled in parallel and
* not in sequence.
*
* @author Olivier Liechti
*/
public class ConcurrentHttpServerTest extends HttpServerTest {
final static Logger LOG = Logger.getLogger(ConcurrentHttpServerTest.class.getName());
/**
* The HTTP server should be able to handle multiple clients in parallel. To test this
* behavior, we submit 3 requests in 3 different threads and target the "/steaming" URI.
* Read carefully the body of the response, you need to respect that syntax. Note that
* System.currentTimeMillis() has been used when sending the first and last line in the
* body. Notice that there are 3 lines starting with "Here is one part" because the
* query string param "iterations" had a value of 3. Notice that
* 1397669533261-1397669530259 = 3002 (which is a bit more than 3 iterations * 1000 ms
* of sleep time per iteration).
*
* --------------------------------------------------------------------
* The client sends this request (3 iterations, sleep time of 1 second)
* --------------------------------------------------------------------
* HTTP/1.1 200 OK
* Content-type: text/plain
* START
* END
* GET /streaming?iterations=3&sleepTime=1000 HTTP/1.1
* Host: localhost
*
* --------------------------------------------------------------------------------------------------------------------
* The server sends this response (System.currentTimeMillis() called on first line and last line, 1 line per iteration)
* --------------------------------------------------------------------------------------------------------------------
* HTTP/1.1 200 OK
* Connection: close
* Content-type: text/plain
*
* START 1397669530259
* Here is one part of the message: 0
* Here is one part of the message: 1
* Here is one part of the message: 2
* END 1397669533261
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public void theHttpServerShouldHandleConcurrentClients() throws IOException, InterruptedException {
IHttpServer server = new HttpServer(rootDirectory, port);
server.start();
int iterations = 5;
long sleepTime = 500;
long expectedResponseTime = iterations * sleepTime;
// for the test, we accept a difference of 10% between the estimated time
// and the measured time
long margin = expectedResponseTime / 10;
// Your server should detect "streaming" as the target resource. It should extract the value of
// iterations and sleepTime from the query string in the target URI. It should then use these
// values when implementing the generation of the response. It should take a little bit more than
// iterations * sleepTime milliseconds for the server to generate 1 response. It should take a little
// bit more than iterations * sleepTime milliseconds for the server to generate 3 responses.
String url = server.getRootUrl() + "streaming?iterations=" + iterations + "&sleepTime=" + sleepTime;
// We will send the requests in multiple threads
Thread t1 = createClientThread(url);
Thread t2 = createClientThread(url);
Thread t3 = createClientThread(url);
// Let's start the timer and send the requests...
long startTime = System.currentTimeMillis();
t1.start();
t2.start();
t3.start();
// Let's wait for the 3 requests to have been handled by the server and take the time...
t1.join();
t2.join();
t3.join();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
assertTrue(Math.abs(duration - expectedResponseTime) < margin);
server.stop();
}
private Thread createClientThread(final String url) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
long clientStartTime = System.currentTimeMillis();
byte[] response = fetchUrl(url);
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response)));
String firstLine = br.readLine();
String lastLine = null;
String line = br.readLine();
while (line != null) {
lastLine = line;
line = br.readLine();
}
long clientEndTime = System.currentTimeMillis();
long clientDuration = clientEndTime - clientStartTime;
long serverStartTime = Long.parseLong(firstLine.split(" ")[1]);
long serverEndTime = Long.parseLong(lastLine.split(" ")[1]);
long serverDuration = serverEndTime - serverStartTime;
assertTrue(Math.abs(serverDuration - 10000) < 1000);
assertTrue(Math.abs(clientDuration - 10000) < 1000);
} catch (IOException ex) {
Logger.getLogger(HttpServerTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
return t;
}}
| Fixed wrong assertion (https://github.com/wasadigi/Teaching-HEIGVD-RES/issues/4) | labs/06-HttpImplementation/HttpLibraryTest/test/ch/heigvd/res/http/test/ConcurrentHttpServerTest.java | Fixed wrong assertion (https://github.com/wasadigi/Teaching-HEIGVD-RES/issues/4) | <ide><path>abs/06-HttpImplementation/HttpLibraryTest/test/ch/heigvd/res/http/test/ConcurrentHttpServerTest.java
<ide> long serverStartTime = Long.parseLong(firstLine.split(" ")[1]);
<ide> long serverEndTime = Long.parseLong(lastLine.split(" ")[1]);
<ide> long serverDuration = serverEndTime - serverStartTime;
<del> assertTrue(Math.abs(serverDuration - 10000) < 1000);
<del> assertTrue(Math.abs(clientDuration - 10000) < 1000);
<add> assertTrue(Math.abs(serverDuration - clientDuration) < 1000);
<ide> } catch (IOException ex) {
<ide> Logger.getLogger(HttpServerTest.class.getName()).log(Level.SEVERE, null, ex);
<ide> } |
|
Java | apache-2.0 | c78e91e07d4e306b91868a9bdee6d7e8e1e5349a | 0 | asedunov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,allotria/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,asedunov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,asedunov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,signed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,hurricup/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,semonte/intellij-community,apixandru/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,semonte/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fitermay/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,FHannes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,FHannes/intellij-community,fitermay/intellij-community,fitermay/intellij-community,xfournet/intellij-community,hurricup/intellij-community,asedunov/intellij-community,da1z/intellij-community,signed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,youdonghai/intellij-community | /*
* Copyright 2000-2016 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.openapi.vcs.ex;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.command.undo.UndoConstants;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.CalledWithWriteLock;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import static com.intellij.diff.util.DiffUtil.getLineCount;
import static com.intellij.openapi.localVcs.UpToDateLineNumberProvider.ABSENT_LINE_NUMBER;
/**
* @author irengrig
* author: lesya
*/
@SuppressWarnings({"MethodMayBeStatic", "FieldAccessedSynchronizedAndUnsynchronized"})
public class LineStatusTracker {
public enum Mode {DEFAULT, SMART, SILENT}
public static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.ex.LineStatusTracker");
private static final Key<CanNotCalculateDiffPanel> PANEL_KEY =
new Key<CanNotCalculateDiffPanel>("LineStatusTracker.CanNotCalculateDiffPanel");
// all variables should be modified in EDT and under LOCK
// read access allowed from EDT or while holding LOCK
private final Object LOCK = new Object();
@NotNull private final Project myProject;
@NotNull private final Document myDocument;
@NotNull private final Document myVcsDocument;
@NotNull private final VirtualFile myVirtualFile;
@NotNull private final Application myApplication;
@NotNull private final FileEditorManager myFileEditorManager;
@NotNull private final VcsDirtyScopeManager myVcsDirtyScopeManager;
@NotNull private final MyDocumentListener myDocumentListener;
@NotNull private final ApplicationAdapter myApplicationListener;
private boolean myInitialized;
private boolean myDuringRollback;
private boolean myBulkUpdate;
private boolean myAnathemaThrown;
private boolean myReleased;
@NotNull private Mode myMode;
@NotNull private List<Range> myRanges;
@Nullable private DirtyRange myDirtyRange;
private LineStatusTracker(@NotNull final Document document,
@NotNull final Project project,
@NotNull final VirtualFile virtualFile,
@NotNull final Mode mode) {
myDocument = document;
myProject = project;
myVirtualFile = virtualFile;
myMode = mode;
myApplication = ApplicationManager.getApplication();
myFileEditorManager = FileEditorManager.getInstance(myProject);
myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
myDocumentListener = new MyDocumentListener();
myDocument.addDocumentListener(myDocumentListener);
myApplicationListener = new MyApplicationListener();
ApplicationManager.getApplication().addApplicationListener(myApplicationListener);
myRanges = new ArrayList<Range>();
myVcsDocument = new DocumentImpl("", true);
myVcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
}
public static LineStatusTracker createOn(@NotNull VirtualFile virtualFile,
@NotNull Document document,
@NotNull Project project,
@NotNull Mode mode) {
return new LineStatusTracker(document, project, virtualFile, mode);
}
@CalledInAwt
public void setBaseRevision(@NotNull final String vcsContent) {
myApplication.assertIsDispatchThread();
if (myReleased) return;
synchronized (LOCK) {
try {
myVcsDocument.setReadOnly(false);
myVcsDocument.setText(vcsContent);
myVcsDocument.setReadOnly(true);
}
finally {
myInitialized = true;
}
reinstallRanges();
}
}
@CalledInAwt
private void reinstallRanges() {
if (!myInitialized || myReleased || myBulkUpdate) return;
destroyRanges();
try {
myRanges = RangesBuilder.createRanges(myDocument, myVcsDocument, myMode == Mode.SMART);
for (final Range range : myRanges) {
createHighlighter(range);
}
if (myRanges.isEmpty()) {
markFileUnchanged();
}
}
catch (FilesTooBigForDiffException e) {
installAnathema();
}
}
@CalledInAwt
private void destroyRanges() {
removeAnathema();
for (Range range : myRanges) {
disposeHighlighter(range);
}
myRanges = Collections.emptyList();
myDirtyRange = null;
}
@CalledInAwt
private void installAnathema() {
myAnathemaThrown = true;
final FileEditor[] editors = myFileEditorManager.getAllEditors(myVirtualFile);
for (FileEditor editor : editors) {
CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
if (panel == null) {
final CanNotCalculateDiffPanel newPanel = new CanNotCalculateDiffPanel();
editor.putUserData(PANEL_KEY, newPanel);
myFileEditorManager.addTopComponent(editor, newPanel);
}
}
}
@CalledInAwt
private void removeAnathema() {
if (!myAnathemaThrown) return;
myAnathemaThrown = false;
final FileEditor[] editors = myFileEditorManager.getEditors(myVirtualFile);
for (FileEditor editor : editors) {
final CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
if (panel != null) {
myFileEditorManager.removeTopComponent(editor, panel);
editor.putUserData(PANEL_KEY, null);
}
}
}
@CalledInAwt
public void setMode(@NotNull Mode mode) {
if (myMode == mode) return;
synchronized (LOCK) {
myMode = mode;
reinstallRanges();
}
}
@CalledInAwt
private void disposeHighlighter(@NotNull Range range) {
try {
range.invalidate();
RangeHighlighter highlighter = range.getHighlighter();
if (highlighter != null) {
range.setHighlighter(null);
highlighter.dispose();
}
}
catch (Exception e) {
LOG.error(e);
}
}
@CalledInAwt
private void createHighlighter(@NotNull Range range) {
myApplication.assertIsDispatchThread();
LOG.assertTrue(!myReleased, "Already released");
if (range.getHighlighter() != null) {
LOG.error("Multiple highlighters registered for the same Range");
return;
}
if (myMode == Mode.SILENT) return;
int first =
range.getLine1() >= getLineCount(myDocument) ? myDocument.getTextLength() : myDocument.getLineStartOffset(range.getLine1());
int second =
range.getLine2() >= getLineCount(myDocument) ? myDocument.getTextLength() : myDocument.getLineStartOffset(range.getLine2());
MarkupModel markupModel = DocumentMarkupModel.forDocument(myDocument, myProject, true);
RangeHighlighter highlighter = LineStatusMarkerRenderer.createRangeHighlighter(range, new TextRange(first, second), markupModel);
highlighter.setLineMarkerRenderer(LineStatusMarkerRenderer.createRenderer(range, (editor) -> {
return new LineStatusTrackerDrawing.MyLineStatusMarkerPopup(this, editor, range);
}));
highlighter.setEditorFilter(MarkupEditorFilterFactory.createIsNotDiffFilter());
range.setHighlighter(highlighter);
}
private boolean tryValidate() {
if (myApplication.isDispatchThread()) updateRanges();
return isValid();
}
public boolean isOperational() {
synchronized (LOCK) {
return myInitialized && !myReleased;
}
}
public boolean isValid() {
synchronized (LOCK) {
return !isSuppressed() && myDirtyRange == null;
}
}
private boolean isSuppressed() {
return !myInitialized || myReleased || myAnathemaThrown || myBulkUpdate || myDuringRollback;
}
public void release() {
Runnable runnable = () -> {
if (myReleased) return;
LOG.assertTrue(!myDuringRollback);
synchronized (LOCK) {
myReleased = true;
myDocument.removeDocumentListener(myDocumentListener);
ApplicationManager.getApplication().removeApplicationListener(myApplicationListener);
destroyRanges();
}
};
if (myApplication.isDispatchThread() && !myDuringRollback) {
runnable.run();
}
else {
myApplication.invokeLater(runnable);
}
}
@NotNull
public Project getProject() {
return myProject;
}
@NotNull
public Document getDocument() {
return myDocument;
}
@NotNull
public Document getVcsDocument() {
return myVcsDocument;
}
@NotNull
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@NotNull
@CalledInAwt
public Mode getMode() {
return myMode;
}
@CalledInAwt
public boolean isSilentMode() {
return myMode == Mode.SILENT;
}
/**
* Ranges can be modified without taking the write lock, so calling this method twice not from EDT can produce different results.
*/
@Nullable
public List<Range> getRanges() {
synchronized (LOCK) {
if (!tryValidate()) return null;
myApplication.assertReadAccessAllowed();
List<Range> result = new ArrayList<>(myRanges.size());
for (Range range : myRanges) {
result.add(new Range(range));
}
return result;
}
}
@CalledInAwt
public void startBulkUpdate() {
if (myReleased) return;
synchronized (LOCK) {
myBulkUpdate = true;
destroyRanges();
}
}
@CalledInAwt
public void finishBulkUpdate() {
if (myReleased) return;
synchronized (LOCK) {
myBulkUpdate = false;
reinstallRanges();
}
}
private void markFileUnchanged() {
// later to avoid saving inside document change event processing.
TransactionGuard.getInstance().submitTransactionLater(myProject, () -> {
FileDocumentManager.getInstance().saveDocument(myDocument);
boolean stillEmpty = !isValid() || myRanges.isEmpty();
if (stillEmpty) {
// file was modified, and now it's not -> dirty local change
myVcsDirtyScopeManager.fileDirty(myVirtualFile);
}
});
}
@CalledInAwt
private void updateRanges() {
if (isSuppressed()) return;
if (myDirtyRange != null) {
synchronized (LOCK) {
try {
doUpdateRanges(myDirtyRange.line1, myDirtyRange.line2, myDirtyRange.lineShift, myDirtyRange.beforeTotalLines);
myDirtyRange = null;
}
catch (Exception e) {
LOG.error(e);
reinstallRanges();
}
}
}
}
private class MyApplicationListener extends ApplicationAdapter {
private int myWriteActionDepth = 0;
@Override
public void writeActionStarted(@NotNull Object action) {
myWriteActionDepth++;
}
@Override
public void writeActionFinished(@NotNull Object action) {
myWriteActionDepth = Math.max(myWriteActionDepth - 1, 0);
if (myWriteActionDepth == 0) {
updateRanges();
}
}
}
private class MyDocumentListener extends DocumentAdapter {
/*
* beforeWriteLock beforeChange Current
* | | |
* | | line1 |
* updatedLine1 +============+-------------+ newLine1
* | | |
* r.line1 +------------+ oldLine1 |
* | | |
* | old | |
* | dirty | |
* | | oldLine2 |
* r.line2 +------------+ ----+ newLine2
* | | / |
* updatedLine2 +============+-------- |
* line2
*/
private int myLine1;
private int myLine2;
private int myBeforeTotalLines;
@Override
public void beforeDocumentChange(DocumentEvent e) {
if (isSuppressed()) return;
assert myDocument == e.getDocument();
myLine1 = myDocument.getLineNumber(e.getOffset());
if (e.getOldLength() == 0) {
myLine2 = myLine1 + 1;
}
else {
myLine2 = myDocument.getLineNumber(e.getOffset() + e.getOldLength()) + 1;
}
myBeforeTotalLines = getLineCount(myDocument);
}
@Override
public void documentChanged(final DocumentEvent e) {
myApplication.assertIsDispatchThread();
if (isSuppressed()) return;
assert myDocument == e.getDocument();
synchronized (LOCK) {
int newLine1 = myLine1;
int newLine2;
if (e.getNewLength() == 0) {
newLine2 = newLine1 + 1;
}
else {
newLine2 = myDocument.getLineNumber(e.getOffset() + e.getNewLength()) + 1;
}
int linesShift = (newLine2 - newLine1) - (myLine2 - myLine1);
int[] fixed = fixRanges(e, myLine1, myLine2);
int line1 = fixed[0];
int line2 = fixed[1];
if (myDirtyRange == null) {
myDirtyRange = new DirtyRange(line1, line2, linesShift, myBeforeTotalLines);
}
else {
int oldLine1 = myDirtyRange.line1;
int oldLine2 = myDirtyRange.line2 + myDirtyRange.lineShift;
int updatedLine1 = myDirtyRange.line1 - Math.max(oldLine1 - line1, 0);
int updatedLine2 = myDirtyRange.line2 + Math.max(line2 - oldLine2, 0);
myDirtyRange = new DirtyRange(updatedLine1, updatedLine2, linesShift + myDirtyRange.lineShift, myDirtyRange.beforeTotalLines);
}
}
}
}
@NotNull
private int[] fixRanges(@NotNull DocumentEvent e, int line1, int line2) {
CharSequence document = myDocument.getCharsSequence();
int offset = e.getOffset();
if (e.getOldLength() == 0 && e.getNewLength() != 0) {
if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
return new int[]{line1, line2 - 1};
}
if (StringUtil.startsWithChar(e.getNewFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
return new int[]{line1 + 1, line2};
}
}
if (e.getOldLength() != 0 && e.getNewLength() == 0) {
if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
return new int[]{line1, line2 - 1};
}
if (StringUtil.startsWithChar(e.getOldFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
return new int[]{line1 + 1, line2};
}
}
return new int[]{line1, line2};
}
private static boolean isNewline(int offset, @NotNull CharSequence sequence) {
if (offset < 0) return false;
if (offset >= sequence.length()) return false;
return sequence.charAt(offset) == '\n';
}
private void doUpdateRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift,
int beforeTotalLines) {
LOG.assertTrue(!myReleased);
List<Range> rangesBeforeChange = new ArrayList<Range>();
List<Range> rangesAfterChange = new ArrayList<Range>();
List<Range> changedRanges = new ArrayList<Range>();
sortRanges(beforeChangedLine1, beforeChangedLine2, linesShift, rangesBeforeChange, changedRanges, rangesAfterChange);
Range firstChangedRange = ContainerUtil.getFirstItem(changedRanges);
Range lastChangedRange = ContainerUtil.getLastItem(changedRanges);
if (firstChangedRange != null && firstChangedRange.getLine1() < beforeChangedLine1) {
beforeChangedLine1 = firstChangedRange.getLine1();
}
if (lastChangedRange != null && lastChangedRange.getLine2() > beforeChangedLine2) {
beforeChangedLine2 = lastChangedRange.getLine2();
}
doUpdateRanges(beforeChangedLine1, beforeChangedLine2, linesShift, beforeTotalLines,
rangesBeforeChange, changedRanges, rangesAfterChange);
}
private void doUpdateRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift, // before -> after
int beforeTotalLines,
@NotNull List<Range> rangesBefore,
@NotNull List<Range> changedRanges,
@NotNull List<Range> rangesAfter) {
try {
int vcsTotalLines = getLineCount(myVcsDocument);
Range lastRangeBefore = ContainerUtil.getLastItem(rangesBefore);
Range firstRangeAfter = ContainerUtil.getFirstItem(rangesAfter);
//noinspection UnnecessaryLocalVariable
int afterChangedLine1 = beforeChangedLine1;
int afterChangedLine2 = beforeChangedLine2 + linesShift;
int vcsLine1 = getVcsLine1(lastRangeBefore, beforeChangedLine1);
int vcsLine2 = getVcsLine2(firstRangeAfter, beforeChangedLine2, beforeTotalLines, vcsTotalLines);
List<Range> newChangedRanges = getNewChangedRanges(afterChangedLine1, afterChangedLine2, vcsLine1, vcsLine2);
shiftRanges(rangesAfter, linesShift);
if (!changedRanges.equals(newChangedRanges)) {
myRanges = new ArrayList<Range>(rangesBefore.size() + newChangedRanges.size() + rangesAfter.size());
myRanges.addAll(rangesBefore);
myRanges.addAll(newChangedRanges);
myRanges.addAll(rangesAfter);
for (Range range : changedRanges) {
disposeHighlighter(range);
}
for (Range range : newChangedRanges) {
createHighlighter(range);
}
if (myRanges.isEmpty()) {
markFileUnchanged();
}
}
}
catch (ProcessCanceledException ignore) {
}
catch (FilesTooBigForDiffException e1) {
destroyRanges();
installAnathema();
}
}
private static int getVcsLine1(@Nullable Range range, int line) {
return range == null ? line : line + range.getVcsLine2() - range.getLine2();
}
private static int getVcsLine2(@Nullable Range range, int line, int totalLinesBefore, int totalLinesAfter) {
return range == null ? totalLinesAfter - totalLinesBefore + line : line + range.getVcsLine1() - range.getLine1();
}
private List<Range> getNewChangedRanges(int changedLine1, int changedLine2, int vcsLine1, int vcsLine2)
throws FilesTooBigForDiffException {
if (changedLine1 == changedLine2 && vcsLine1 == vcsLine2) {
return Collections.emptyList();
}
if (changedLine1 == changedLine2) {
return Collections.singletonList(new Range(changedLine1, changedLine2, vcsLine1, vcsLine2));
}
if (vcsLine1 == vcsLine2) {
return Collections.singletonList(new Range(changedLine1, changedLine2, vcsLine1, vcsLine2));
}
List<String> lines = DiffUtil.getLines(myDocument, changedLine1, changedLine2);
List<String> vcsLines = DiffUtil.getLines(myVcsDocument, vcsLine1, vcsLine2);
return RangesBuilder.createRanges(lines, vcsLines, changedLine1, vcsLine1, myMode == Mode.SMART);
}
private static void shiftRanges(@NotNull List<Range> rangesAfterChange, int shift) {
for (final Range range : rangesAfterChange) {
range.shift(shift);
}
}
private void sortRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift,
@NotNull List<Range> rangesBeforeChange,
@NotNull List<Range> changedRanges,
@NotNull List<Range> rangesAfterChange) {
int lastBefore = -1;
int firstAfter = myRanges.size();
for (int i = 0; i < myRanges.size(); i++) {
Range range = myRanges.get(i);
if (range.getLine2() < beforeChangedLine1) {
lastBefore = i;
}
else if (range.getLine1() > beforeChangedLine2) {
firstAfter = i;
break;
}
}
if (Registry.is("diff.status.tracker.skip.spaces")) {
// Expand on ranges, that are separated from changed lines only by whitespaces
while (lastBefore != -1) {
int firstChangedLine = beforeChangedLine1;
if (lastBefore + 1 < myRanges.size()) {
Range firstChanged = myRanges.get(lastBefore + 1);
firstChangedLine = Math.min(firstChangedLine, firstChanged.getLine1());
}
if (!isLineRangeEmpty(myDocument, myRanges.get(lastBefore).getLine2(), firstChangedLine)) {
break;
}
lastBefore--;
}
while (firstAfter != myRanges.size()) {
int firstUnchangedLineAfter = beforeChangedLine2 + linesShift;
if (firstAfter > 0) {
Range lastChanged = myRanges.get(firstAfter - 1);
firstUnchangedLineAfter = Math.max(firstUnchangedLineAfter, lastChanged.getLine2() + linesShift);
}
if (!isLineRangeEmpty(myDocument, firstUnchangedLineAfter, myRanges.get(firstAfter).getLine1() + linesShift)) {
break;
}
firstAfter++;
}
}
for (int i = 0; i < myRanges.size(); i++) {
Range range = myRanges.get(i);
if (i <= lastBefore) {
rangesBeforeChange.add(range);
}
else if (i >= firstAfter) {
rangesAfterChange.add(range);
}
else {
changedRanges.add(range);
}
}
}
private static boolean isLineRangeEmpty(@NotNull Document document, int line1, int line2) {
int lineCount = getLineCount(document);
int startOffset = line1 == lineCount ? document.getTextLength() : document.getLineStartOffset(line1);
int endOffset = line2 == lineCount ? document.getTextLength() : document.getLineStartOffset(line2);
CharSequence interval = document.getImmutableCharSequence().subSequence(startOffset, endOffset);
return StringUtil.isEmptyOrSpaces(interval);
}
@Nullable
public Range getNextRange(Range range) {
synchronized (LOCK) {
if (!tryValidate()) return null;
final int index = myRanges.indexOf(range);
if (index == myRanges.size() - 1) return null;
return myRanges.get(index + 1);
}
}
@Nullable
public Range getPrevRange(Range range) {
synchronized (LOCK) {
if (!tryValidate()) return null;
final int index = myRanges.indexOf(range);
if (index <= 0) return null;
return myRanges.get(index - 1);
}
}
@Nullable
public Range getNextRange(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (Range range : myRanges) {
if (line < range.getLine2() && !range.isSelectedByLine(line)) {
return range;
}
}
return null;
}
}
@Nullable
public Range getPrevRange(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (int i = myRanges.size() - 1; i >= 0; i--) {
Range range = myRanges.get(i);
if (line > range.getLine1() && !range.isSelectedByLine(line)) {
return range;
}
}
return null;
}
}
@Nullable
public Range getRangeForLine(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (final Range range : myRanges) {
if (range.isSelectedByLine(line)) return range;
}
return null;
}
}
private void doRollbackRange(@NotNull Range range) {
DiffUtil.applyModification(myDocument, range.getLine1(), range.getLine2(), myVcsDocument, range.getVcsLine1(), range.getVcsLine2());
markLinesUnchanged(range.getLine1(), range.getLine1() + range.getVcsLine2() - range.getVcsLine1());
}
private void markLinesUnchanged(int startLine, int endLine) {
if (myDocument.getTextLength() == 0) return; // empty document has no lines
if (startLine == endLine) return;
((DocumentImpl)myDocument).clearLineModificationFlags(startLine, endLine);
}
@CalledWithWriteLock
public void rollbackChanges(@NotNull Range range) {
rollbackChanges(Collections.singletonList(range));
}
@CalledWithWriteLock
public void rollbackChanges(@NotNull final BitSet lines) {
List<Range> toRollback = new ArrayList<Range>();
for (Range range : myRanges) {
boolean check = DiffUtil.isSelectedByLine(lines, range.getLine1(), range.getLine2());
if (check) {
toRollback.add(range);
}
}
rollbackChanges(toRollback);
}
/**
* @param ranges - sorted list of ranges to rollback
*/
@CalledWithWriteLock
private void rollbackChanges(@NotNull final List<Range> ranges) {
runBulkRollback(() -> {
Range first = null;
Range last = null;
int shift = 0;
for (Range range : ranges) {
if (!range.isValid()) {
LOG.warn("Rollback of invalid range");
break;
}
if (first == null) {
first = range;
}
last = range;
Range shiftedRange = new Range(range);
shiftedRange.shift(shift);
doRollbackRange(shiftedRange);
shift += (range.getVcsLine2() - range.getVcsLine1()) - (range.getLine2() - range.getLine1());
}
if (first != null) {
int beforeChangedLine1 = first.getLine1();
int beforeChangedLine2 = last.getLine2();
int beforeTotalLines = getLineCount(myDocument) - shift;
doUpdateRanges(beforeChangedLine1, beforeChangedLine2, shift, beforeTotalLines);
}
});
}
@CalledWithWriteLock
public void rollbackAllChanges() {
runBulkRollback(() -> {
myDocument.setText(myVcsDocument.getText());
destroyRanges();
markFileUnchanged();
});
}
@CalledWithWriteLock
private void runBulkRollback(@NotNull Runnable task) {
myApplication.assertWriteAccessAllowed();
if (!tryValidate()) return;
synchronized (LOCK) {
try {
myDuringRollback = true;
task.run();
}
catch (Error | RuntimeException e) {
reinstallRanges();
throw e;
}
finally {
myDuringRollback = false;
}
}
}
@NotNull
public CharSequence getCurrentContent(@NotNull Range range) {
TextRange textRange = getCurrentTextRange(range);
final int startOffset = textRange.getStartOffset();
final int endOffset = textRange.getEndOffset();
return myDocument.getImmutableCharSequence().subSequence(startOffset, endOffset);
}
@NotNull
public CharSequence getVcsContent(@NotNull Range range) {
TextRange textRange = getVcsTextRange(range);
final int startOffset = textRange.getStartOffset();
final int endOffset = textRange.getEndOffset();
return myVcsDocument.getImmutableCharSequence().subSequence(startOffset, endOffset);
}
@NotNull
public TextRange getCurrentTextRange(@NotNull Range range) {
synchronized (LOCK) {
assert isValid();
if (!range.isValid()) {
LOG.warn("Current TextRange of invalid range");
}
return DiffUtil.getLinesRange(myDocument, range.getLine1(), range.getLine2());
}
}
@NotNull
public TextRange getVcsTextRange(@NotNull Range range) {
synchronized (LOCK) {
assert isValid();
if (!range.isValid()) {
LOG.warn("Vcs TextRange of invalid range");
}
return DiffUtil.getLinesRange(myVcsDocument, range.getVcsLine1(), range.getVcsLine2());
}
}
public boolean isLineModified(int line) {
return isRangeModified(line, line + 1);
}
public boolean isRangeModified(int line1, int line2) {
synchronized (LOCK) {
if (!tryValidate()) return false;
if (line1 == line2) return false;
assert line1 < line2;
for (Range range : myRanges) {
if (range.getLine1() >= line2) return false;
if (range.getLine2() > line1) return true;
}
return false;
}
}
public int transferLineToFromVcs(int line, boolean approximate) {
return transferLine(line, approximate, true);
}
public int transferLineToVcs(int line, boolean approximate) {
return transferLine(line, approximate, false);
}
private int transferLine(int line, boolean approximate, boolean fromVcs) {
synchronized (LOCK) {
if (!tryValidate()) return approximate ? line : ABSENT_LINE_NUMBER;
int result = line;
for (Range range : myRanges) {
int startLine1 = fromVcs ? range.getVcsLine1() : range.getLine1();
int endLine1 = fromVcs ? range.getVcsLine2() : range.getLine2();
int startLine2 = fromVcs ? range.getLine1() : range.getVcsLine1();
int endLine2 = fromVcs ? range.getLine2() : range.getVcsLine2();
if (startLine1 <= line && endLine1 > line) {
return approximate ? startLine2 : ABSENT_LINE_NUMBER;
}
if (endLine1 > line) return result;
int length1 = endLine1 - startLine1;
int length2 = endLine2 - startLine2;
result += length2 - length1;
}
return result;
}
}
private static class DirtyRange {
public final int line1;
public final int line2;
public final int lineShift;
public final int beforeTotalLines;
public DirtyRange(int line1, int line2, int lineShift, int beforeTotalLines) {
this.line1 = line1;
this.line2 = line2;
this.lineShift = lineShift;
this.beforeTotalLines = beforeTotalLines;
}
}
private static class CanNotCalculateDiffPanel extends EditorNotificationPanel {
public CanNotCalculateDiffPanel() {
myLabel.setText("Can not highlight changed lines. File is too big and there are too many changes.");
}
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java | /*
* Copyright 2000-2016 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.openapi.vcs.ex;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.command.undo.UndoConstants;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.CalledWithWriteLock;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import static com.intellij.diff.util.DiffUtil.getLineCount;
import static com.intellij.openapi.localVcs.UpToDateLineNumberProvider.ABSENT_LINE_NUMBER;
/**
* @author irengrig
* author: lesya
*/
@SuppressWarnings({"MethodMayBeStatic", "FieldAccessedSynchronizedAndUnsynchronized"})
public class LineStatusTracker {
public enum Mode {DEFAULT, SMART, SILENT}
public static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.ex.LineStatusTracker");
private static final Key<CanNotCalculateDiffPanel> PANEL_KEY =
new Key<CanNotCalculateDiffPanel>("LineStatusTracker.CanNotCalculateDiffPanel");
// all variables should be modified in EDT and under LOCK
// read access allowed from EDT or while holding LOCK
private final Object LOCK = new Object();
@NotNull private final Project myProject;
@NotNull private final Document myDocument;
@NotNull private final Document myVcsDocument;
@NotNull private final VirtualFile myVirtualFile;
@NotNull private final Application myApplication;
@NotNull private final FileEditorManager myFileEditorManager;
@NotNull private final VcsDirtyScopeManager myVcsDirtyScopeManager;
@NotNull private final MyDocumentListener myDocumentListener;
@NotNull private final ApplicationAdapter myApplicationListener;
private boolean myInitialized;
private boolean myDuringRollback;
private boolean myBulkUpdate;
private boolean myAnathemaThrown;
private boolean myReleased;
@NotNull private Mode myMode;
@NotNull private List<Range> myRanges;
@Nullable private DirtyRange myDirtyRange;
private LineStatusTracker(@NotNull final Document document,
@NotNull final Project project,
@NotNull final VirtualFile virtualFile,
@NotNull final Mode mode) {
myDocument = document;
myProject = project;
myVirtualFile = virtualFile;
myMode = mode;
myApplication = ApplicationManager.getApplication();
myFileEditorManager = FileEditorManager.getInstance(myProject);
myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
myDocumentListener = new MyDocumentListener();
myDocument.addDocumentListener(myDocumentListener);
myApplicationListener = new MyApplicationListener();
ApplicationManager.getApplication().addApplicationListener(myApplicationListener);
myRanges = new ArrayList<Range>();
myVcsDocument = new DocumentImpl("", true);
myVcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
}
public static LineStatusTracker createOn(@NotNull VirtualFile virtualFile,
@NotNull Document document,
@NotNull Project project,
@NotNull Mode mode) {
return new LineStatusTracker(document, project, virtualFile, mode);
}
@CalledInAwt
public void setBaseRevision(@NotNull final String vcsContent) {
myApplication.assertIsDispatchThread();
if (myReleased) return;
synchronized (LOCK) {
try {
myVcsDocument.setReadOnly(false);
myVcsDocument.setText(vcsContent);
myVcsDocument.setReadOnly(true);
}
finally {
myInitialized = true;
}
reinstallRanges();
}
}
@CalledInAwt
private void reinstallRanges() {
if (!myInitialized || myReleased || myBulkUpdate) return;
destroyRanges();
try {
myRanges = RangesBuilder.createRanges(myDocument, myVcsDocument, myMode == Mode.SMART);
for (final Range range : myRanges) {
createHighlighter(range);
}
if (myRanges.isEmpty()) {
markFileUnchanged();
}
}
catch (FilesTooBigForDiffException e) {
installAnathema();
}
}
@CalledInAwt
private void destroyRanges() {
removeAnathema();
for (Range range : myRanges) {
disposeHighlighter(range);
}
myRanges = Collections.emptyList();
myDirtyRange = null;
}
@CalledInAwt
private void installAnathema() {
myAnathemaThrown = true;
final FileEditor[] editors = myFileEditorManager.getAllEditors(myVirtualFile);
for (FileEditor editor : editors) {
CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
if (panel == null) {
final CanNotCalculateDiffPanel newPanel = new CanNotCalculateDiffPanel();
editor.putUserData(PANEL_KEY, newPanel);
myFileEditorManager.addTopComponent(editor, newPanel);
}
}
}
@CalledInAwt
private void removeAnathema() {
if (!myAnathemaThrown) return;
myAnathemaThrown = false;
final FileEditor[] editors = myFileEditorManager.getEditors(myVirtualFile);
for (FileEditor editor : editors) {
final CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
if (panel != null) {
myFileEditorManager.removeTopComponent(editor, panel);
editor.putUserData(PANEL_KEY, null);
}
}
}
@CalledInAwt
public void setMode(@NotNull Mode mode) {
if (myMode == mode) return;
synchronized (LOCK) {
myMode = mode;
reinstallRanges();
}
}
@CalledInAwt
private void disposeHighlighter(@NotNull Range range) {
try {
range.invalidate();
RangeHighlighter highlighter = range.getHighlighter();
if (highlighter != null) {
range.setHighlighter(null);
highlighter.dispose();
}
}
catch (Exception e) {
LOG.error(e);
}
}
@CalledInAwt
private void createHighlighter(@NotNull Range range) {
myApplication.assertIsDispatchThread();
LOG.assertTrue(!myReleased, "Already released");
if (range.getHighlighter() != null) {
LOG.error("Multiple highlighters registered for the same Range");
return;
}
if (myMode == Mode.SILENT) return;
int first =
range.getLine1() >= getLineCount(myDocument) ? myDocument.getTextLength() : myDocument.getLineStartOffset(range.getLine1());
int second =
range.getLine2() >= getLineCount(myDocument) ? myDocument.getTextLength() : myDocument.getLineStartOffset(range.getLine2());
MarkupModel markupModel = DocumentMarkupModel.forDocument(myDocument, myProject, true);
RangeHighlighter highlighter = LineStatusMarkerRenderer.createRangeHighlighter(range, new TextRange(first, second), markupModel);
highlighter.setLineMarkerRenderer(LineStatusMarkerRenderer.createRenderer(range, (editor) -> {
return new LineStatusTrackerDrawing.MyLineStatusMarkerPopup(this, editor, range);
}));
highlighter.setEditorFilter(MarkupEditorFilterFactory.createIsNotDiffFilter());
range.setHighlighter(highlighter);
}
private boolean tryValidate() {
if (myApplication.isDispatchThread()) updateRanges();
return isValid();
}
public boolean isOperational() {
synchronized (LOCK) {
return myInitialized && !myReleased;
}
}
public boolean isValid() {
synchronized (LOCK) {
return !isSuppressed() && myDirtyRange == null;
}
}
private boolean isSuppressed() {
return !myInitialized || myReleased || myAnathemaThrown || myBulkUpdate || myDuringRollback;
}
public void release() {
Runnable runnable = () -> {
if (myReleased) return;
LOG.assertTrue(!myDuringRollback);
synchronized (LOCK) {
myReleased = true;
myDocument.removeDocumentListener(myDocumentListener);
ApplicationManager.getApplication().removeApplicationListener(myApplicationListener);
destroyRanges();
}
};
if (myApplication.isDispatchThread() && !myDuringRollback) {
runnable.run();
}
else {
myApplication.invokeLater(runnable);
}
}
@NotNull
public Project getProject() {
return myProject;
}
@NotNull
public Document getDocument() {
return myDocument;
}
@NotNull
public Document getVcsDocument() {
return myVcsDocument;
}
@NotNull
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@NotNull
@CalledInAwt
public Mode getMode() {
return myMode;
}
@CalledInAwt
public boolean isSilentMode() {
return myMode == Mode.SILENT;
}
/**
* Ranges can be modified without taking the write lock, so calling this method twice not from EDT can produce different results.
*/
@Nullable
public List<Range> getRanges() {
synchronized (LOCK) {
if (!tryValidate()) return null;
myApplication.assertReadAccessAllowed();
List<Range> result = new ArrayList<>(myRanges.size());
for (Range range : myRanges) {
result.add(new Range(range));
}
return result;
}
}
@CalledInAwt
public void startBulkUpdate() {
if (myReleased) return;
synchronized (LOCK) {
myBulkUpdate = true;
destroyRanges();
}
}
@CalledInAwt
public void finishBulkUpdate() {
if (myReleased) return;
synchronized (LOCK) {
myBulkUpdate = false;
reinstallRanges();
}
}
private void markFileUnchanged() {
// later to avoid saving inside document change event processing.
TransactionGuard.getInstance().submitTransactionLater(myProject, () -> {
FileDocumentManager.getInstance().saveDocument(myDocument);
boolean stillEmpty = !isValid() || myRanges.isEmpty();
if (stillEmpty) {
// file was modified, and now it's not -> dirty local change
myVcsDirtyScopeManager.fileDirty(myVirtualFile);
}
});
}
@CalledInAwt
private void updateRanges() {
if (isSuppressed()) return;
if (myDirtyRange != null) {
synchronized (LOCK) {
try {
doUpdateRanges(myDirtyRange.line1, myDirtyRange.line2, myDirtyRange.lineShift, myDirtyRange.beforeTotalLines);
myDirtyRange = null;
}
catch (Exception e) {
LOG.error(e);
reinstallRanges();
}
}
}
}
private class MyApplicationListener extends ApplicationAdapter {
@Override
public void writeActionFinished(@NotNull Object action) {
updateRanges();
}
}
private class MyDocumentListener extends DocumentAdapter {
/*
* beforeWriteLock beforeChange Current
* | | |
* | | line1 |
* updatedLine1 +============+-------------+ newLine1
* | | |
* r.line1 +------------+ oldLine1 |
* | | |
* | old | |
* | dirty | |
* | | oldLine2 |
* r.line2 +------------+ ----+ newLine2
* | | / |
* updatedLine2 +============+-------- |
* line2
*/
private int myLine1;
private int myLine2;
private int myBeforeTotalLines;
@Override
public void beforeDocumentChange(DocumentEvent e) {
if (isSuppressed()) return;
assert myDocument == e.getDocument();
myLine1 = myDocument.getLineNumber(e.getOffset());
if (e.getOldLength() == 0) {
myLine2 = myLine1 + 1;
}
else {
myLine2 = myDocument.getLineNumber(e.getOffset() + e.getOldLength()) + 1;
}
myBeforeTotalLines = getLineCount(myDocument);
}
@Override
public void documentChanged(final DocumentEvent e) {
myApplication.assertIsDispatchThread();
if (isSuppressed()) return;
assert myDocument == e.getDocument();
synchronized (LOCK) {
int newLine1 = myLine1;
int newLine2;
if (e.getNewLength() == 0) {
newLine2 = newLine1 + 1;
}
else {
newLine2 = myDocument.getLineNumber(e.getOffset() + e.getNewLength()) + 1;
}
int linesShift = (newLine2 - newLine1) - (myLine2 - myLine1);
int[] fixed = fixRanges(e, myLine1, myLine2);
int line1 = fixed[0];
int line2 = fixed[1];
if (myDirtyRange == null) {
myDirtyRange = new DirtyRange(line1, line2, linesShift, myBeforeTotalLines);
}
else {
int oldLine1 = myDirtyRange.line1;
int oldLine2 = myDirtyRange.line2 + myDirtyRange.lineShift;
int updatedLine1 = myDirtyRange.line1 - Math.max(oldLine1 - line1, 0);
int updatedLine2 = myDirtyRange.line2 + Math.max(line2 - oldLine2, 0);
myDirtyRange = new DirtyRange(updatedLine1, updatedLine2, linesShift + myDirtyRange.lineShift, myDirtyRange.beforeTotalLines);
}
}
}
}
@NotNull
private int[] fixRanges(@NotNull DocumentEvent e, int line1, int line2) {
CharSequence document = myDocument.getCharsSequence();
int offset = e.getOffset();
if (e.getOldLength() == 0 && e.getNewLength() != 0) {
if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
return new int[]{line1, line2 - 1};
}
if (StringUtil.startsWithChar(e.getNewFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
return new int[]{line1 + 1, line2};
}
}
if (e.getOldLength() != 0 && e.getNewLength() == 0) {
if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
return new int[]{line1, line2 - 1};
}
if (StringUtil.startsWithChar(e.getOldFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
return new int[]{line1 + 1, line2};
}
}
return new int[]{line1, line2};
}
private static boolean isNewline(int offset, @NotNull CharSequence sequence) {
if (offset < 0) return false;
if (offset >= sequence.length()) return false;
return sequence.charAt(offset) == '\n';
}
private void doUpdateRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift,
int beforeTotalLines) {
LOG.assertTrue(!myReleased);
List<Range> rangesBeforeChange = new ArrayList<Range>();
List<Range> rangesAfterChange = new ArrayList<Range>();
List<Range> changedRanges = new ArrayList<Range>();
sortRanges(beforeChangedLine1, beforeChangedLine2, linesShift, rangesBeforeChange, changedRanges, rangesAfterChange);
Range firstChangedRange = ContainerUtil.getFirstItem(changedRanges);
Range lastChangedRange = ContainerUtil.getLastItem(changedRanges);
if (firstChangedRange != null && firstChangedRange.getLine1() < beforeChangedLine1) {
beforeChangedLine1 = firstChangedRange.getLine1();
}
if (lastChangedRange != null && lastChangedRange.getLine2() > beforeChangedLine2) {
beforeChangedLine2 = lastChangedRange.getLine2();
}
doUpdateRanges(beforeChangedLine1, beforeChangedLine2, linesShift, beforeTotalLines,
rangesBeforeChange, changedRanges, rangesAfterChange);
}
private void doUpdateRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift, // before -> after
int beforeTotalLines,
@NotNull List<Range> rangesBefore,
@NotNull List<Range> changedRanges,
@NotNull List<Range> rangesAfter) {
try {
int vcsTotalLines = getLineCount(myVcsDocument);
Range lastRangeBefore = ContainerUtil.getLastItem(rangesBefore);
Range firstRangeAfter = ContainerUtil.getFirstItem(rangesAfter);
//noinspection UnnecessaryLocalVariable
int afterChangedLine1 = beforeChangedLine1;
int afterChangedLine2 = beforeChangedLine2 + linesShift;
int vcsLine1 = getVcsLine1(lastRangeBefore, beforeChangedLine1);
int vcsLine2 = getVcsLine2(firstRangeAfter, beforeChangedLine2, beforeTotalLines, vcsTotalLines);
List<Range> newChangedRanges = getNewChangedRanges(afterChangedLine1, afterChangedLine2, vcsLine1, vcsLine2);
shiftRanges(rangesAfter, linesShift);
if (!changedRanges.equals(newChangedRanges)) {
myRanges = new ArrayList<Range>(rangesBefore.size() + newChangedRanges.size() + rangesAfter.size());
myRanges.addAll(rangesBefore);
myRanges.addAll(newChangedRanges);
myRanges.addAll(rangesAfter);
for (Range range : changedRanges) {
disposeHighlighter(range);
}
for (Range range : newChangedRanges) {
createHighlighter(range);
}
if (myRanges.isEmpty()) {
markFileUnchanged();
}
}
}
catch (ProcessCanceledException ignore) {
}
catch (FilesTooBigForDiffException e1) {
destroyRanges();
installAnathema();
}
}
private static int getVcsLine1(@Nullable Range range, int line) {
return range == null ? line : line + range.getVcsLine2() - range.getLine2();
}
private static int getVcsLine2(@Nullable Range range, int line, int totalLinesBefore, int totalLinesAfter) {
return range == null ? totalLinesAfter - totalLinesBefore + line : line + range.getVcsLine1() - range.getLine1();
}
private List<Range> getNewChangedRanges(int changedLine1, int changedLine2, int vcsLine1, int vcsLine2)
throws FilesTooBigForDiffException {
if (changedLine1 == changedLine2 && vcsLine1 == vcsLine2) {
return Collections.emptyList();
}
if (changedLine1 == changedLine2) {
return Collections.singletonList(new Range(changedLine1, changedLine2, vcsLine1, vcsLine2));
}
if (vcsLine1 == vcsLine2) {
return Collections.singletonList(new Range(changedLine1, changedLine2, vcsLine1, vcsLine2));
}
List<String> lines = DiffUtil.getLines(myDocument, changedLine1, changedLine2);
List<String> vcsLines = DiffUtil.getLines(myVcsDocument, vcsLine1, vcsLine2);
return RangesBuilder.createRanges(lines, vcsLines, changedLine1, vcsLine1, myMode == Mode.SMART);
}
private static void shiftRanges(@NotNull List<Range> rangesAfterChange, int shift) {
for (final Range range : rangesAfterChange) {
range.shift(shift);
}
}
private void sortRanges(int beforeChangedLine1,
int beforeChangedLine2,
int linesShift,
@NotNull List<Range> rangesBeforeChange,
@NotNull List<Range> changedRanges,
@NotNull List<Range> rangesAfterChange) {
int lastBefore = -1;
int firstAfter = myRanges.size();
for (int i = 0; i < myRanges.size(); i++) {
Range range = myRanges.get(i);
if (range.getLine2() < beforeChangedLine1) {
lastBefore = i;
}
else if (range.getLine1() > beforeChangedLine2) {
firstAfter = i;
break;
}
}
if (Registry.is("diff.status.tracker.skip.spaces")) {
// Expand on ranges, that are separated from changed lines only by whitespaces
while (lastBefore != -1) {
int firstChangedLine = beforeChangedLine1;
if (lastBefore + 1 < myRanges.size()) {
Range firstChanged = myRanges.get(lastBefore + 1);
firstChangedLine = Math.min(firstChangedLine, firstChanged.getLine1());
}
if (!isLineRangeEmpty(myDocument, myRanges.get(lastBefore).getLine2(), firstChangedLine)) {
break;
}
lastBefore--;
}
while (firstAfter != myRanges.size()) {
int firstUnchangedLineAfter = beforeChangedLine2 + linesShift;
if (firstAfter > 0) {
Range lastChanged = myRanges.get(firstAfter - 1);
firstUnchangedLineAfter = Math.max(firstUnchangedLineAfter, lastChanged.getLine2() + linesShift);
}
if (!isLineRangeEmpty(myDocument, firstUnchangedLineAfter, myRanges.get(firstAfter).getLine1() + linesShift)) {
break;
}
firstAfter++;
}
}
for (int i = 0; i < myRanges.size(); i++) {
Range range = myRanges.get(i);
if (i <= lastBefore) {
rangesBeforeChange.add(range);
}
else if (i >= firstAfter) {
rangesAfterChange.add(range);
}
else {
changedRanges.add(range);
}
}
}
private static boolean isLineRangeEmpty(@NotNull Document document, int line1, int line2) {
int lineCount = getLineCount(document);
int startOffset = line1 == lineCount ? document.getTextLength() : document.getLineStartOffset(line1);
int endOffset = line2 == lineCount ? document.getTextLength() : document.getLineStartOffset(line2);
CharSequence interval = document.getImmutableCharSequence().subSequence(startOffset, endOffset);
return StringUtil.isEmptyOrSpaces(interval);
}
@Nullable
public Range getNextRange(Range range) {
synchronized (LOCK) {
if (!tryValidate()) return null;
final int index = myRanges.indexOf(range);
if (index == myRanges.size() - 1) return null;
return myRanges.get(index + 1);
}
}
@Nullable
public Range getPrevRange(Range range) {
synchronized (LOCK) {
if (!tryValidate()) return null;
final int index = myRanges.indexOf(range);
if (index <= 0) return null;
return myRanges.get(index - 1);
}
}
@Nullable
public Range getNextRange(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (Range range : myRanges) {
if (line < range.getLine2() && !range.isSelectedByLine(line)) {
return range;
}
}
return null;
}
}
@Nullable
public Range getPrevRange(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (int i = myRanges.size() - 1; i >= 0; i--) {
Range range = myRanges.get(i);
if (line > range.getLine1() && !range.isSelectedByLine(line)) {
return range;
}
}
return null;
}
}
@Nullable
public Range getRangeForLine(int line) {
synchronized (LOCK) {
if (!tryValidate()) return null;
for (final Range range : myRanges) {
if (range.isSelectedByLine(line)) return range;
}
return null;
}
}
private void doRollbackRange(@NotNull Range range) {
DiffUtil.applyModification(myDocument, range.getLine1(), range.getLine2(), myVcsDocument, range.getVcsLine1(), range.getVcsLine2());
markLinesUnchanged(range.getLine1(), range.getLine1() + range.getVcsLine2() - range.getVcsLine1());
}
private void markLinesUnchanged(int startLine, int endLine) {
if (myDocument.getTextLength() == 0) return; // empty document has no lines
if (startLine == endLine) return;
((DocumentImpl)myDocument).clearLineModificationFlags(startLine, endLine);
}
@CalledWithWriteLock
public void rollbackChanges(@NotNull Range range) {
rollbackChanges(Collections.singletonList(range));
}
@CalledWithWriteLock
public void rollbackChanges(@NotNull final BitSet lines) {
List<Range> toRollback = new ArrayList<Range>();
for (Range range : myRanges) {
boolean check = DiffUtil.isSelectedByLine(lines, range.getLine1(), range.getLine2());
if (check) {
toRollback.add(range);
}
}
rollbackChanges(toRollback);
}
/**
* @param ranges - sorted list of ranges to rollback
*/
@CalledWithWriteLock
private void rollbackChanges(@NotNull final List<Range> ranges) {
runBulkRollback(() -> {
Range first = null;
Range last = null;
int shift = 0;
for (Range range : ranges) {
if (!range.isValid()) {
LOG.warn("Rollback of invalid range");
break;
}
if (first == null) {
first = range;
}
last = range;
Range shiftedRange = new Range(range);
shiftedRange.shift(shift);
doRollbackRange(shiftedRange);
shift += (range.getVcsLine2() - range.getVcsLine1()) - (range.getLine2() - range.getLine1());
}
if (first != null) {
int beforeChangedLine1 = first.getLine1();
int beforeChangedLine2 = last.getLine2();
int beforeTotalLines = getLineCount(myDocument) - shift;
doUpdateRanges(beforeChangedLine1, beforeChangedLine2, shift, beforeTotalLines);
}
});
}
@CalledWithWriteLock
public void rollbackAllChanges() {
runBulkRollback(() -> {
myDocument.setText(myVcsDocument.getText());
destroyRanges();
markFileUnchanged();
});
}
@CalledWithWriteLock
private void runBulkRollback(@NotNull Runnable task) {
myApplication.assertWriteAccessAllowed();
if (!tryValidate()) return;
synchronized (LOCK) {
try {
myDuringRollback = true;
task.run();
}
catch (Error | RuntimeException e) {
reinstallRanges();
throw e;
}
finally {
myDuringRollback = false;
}
}
}
@NotNull
public CharSequence getCurrentContent(@NotNull Range range) {
TextRange textRange = getCurrentTextRange(range);
final int startOffset = textRange.getStartOffset();
final int endOffset = textRange.getEndOffset();
return myDocument.getImmutableCharSequence().subSequence(startOffset, endOffset);
}
@NotNull
public CharSequence getVcsContent(@NotNull Range range) {
TextRange textRange = getVcsTextRange(range);
final int startOffset = textRange.getStartOffset();
final int endOffset = textRange.getEndOffset();
return myVcsDocument.getImmutableCharSequence().subSequence(startOffset, endOffset);
}
@NotNull
public TextRange getCurrentTextRange(@NotNull Range range) {
synchronized (LOCK) {
assert isValid();
if (!range.isValid()) {
LOG.warn("Current TextRange of invalid range");
}
return DiffUtil.getLinesRange(myDocument, range.getLine1(), range.getLine2());
}
}
@NotNull
public TextRange getVcsTextRange(@NotNull Range range) {
synchronized (LOCK) {
assert isValid();
if (!range.isValid()) {
LOG.warn("Vcs TextRange of invalid range");
}
return DiffUtil.getLinesRange(myVcsDocument, range.getVcsLine1(), range.getVcsLine2());
}
}
public boolean isLineModified(int line) {
return isRangeModified(line, line + 1);
}
public boolean isRangeModified(int line1, int line2) {
synchronized (LOCK) {
if (!tryValidate()) return false;
if (line1 == line2) return false;
assert line1 < line2;
for (Range range : myRanges) {
if (range.getLine1() >= line2) return false;
if (range.getLine2() > line1) return true;
}
return false;
}
}
public int transferLineToFromVcs(int line, boolean approximate) {
return transferLine(line, approximate, true);
}
public int transferLineToVcs(int line, boolean approximate) {
return transferLine(line, approximate, false);
}
private int transferLine(int line, boolean approximate, boolean fromVcs) {
synchronized (LOCK) {
if (!tryValidate()) return approximate ? line : ABSENT_LINE_NUMBER;
int result = line;
for (Range range : myRanges) {
int startLine1 = fromVcs ? range.getVcsLine1() : range.getLine1();
int endLine1 = fromVcs ? range.getVcsLine2() : range.getLine2();
int startLine2 = fromVcs ? range.getLine1() : range.getVcsLine1();
int endLine2 = fromVcs ? range.getLine2() : range.getVcsLine2();
if (startLine1 <= line && endLine1 > line) {
return approximate ? startLine2 : ABSENT_LINE_NUMBER;
}
if (endLine1 > line) return result;
int length1 = endLine1 - startLine1;
int length2 = endLine2 - startLine2;
result += length2 - length1;
}
return result;
}
}
private static class DirtyRange {
public final int line1;
public final int line2;
public final int lineShift;
public final int beforeTotalLines;
public DirtyRange(int line1, int line2, int lineShift, int beforeTotalLines) {
this.line1 = line1;
this.line2 = line2;
this.lineShift = lineShift;
this.beforeTotalLines = beforeTotalLines;
}
}
private static class CanNotCalculateDiffPanel extends EditorNotificationPanel {
public CanNotCalculateDiffPanel() {
myLabel.setText("Can not highlight changed lines. File is too big and there are too many changes.");
}
}
}
| lst: refresh only after the last of enclosed WriteActions
We don't use afterWriteActionFinished because we want to update inside same WriteLock section.
| platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java | lst: refresh only after the last of enclosed WriteActions | <ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java
<ide> }
<ide>
<ide> private class MyApplicationListener extends ApplicationAdapter {
<add> private int myWriteActionDepth = 0;
<add>
<add> @Override
<add> public void writeActionStarted(@NotNull Object action) {
<add> myWriteActionDepth++;
<add> }
<add>
<ide> @Override
<ide> public void writeActionFinished(@NotNull Object action) {
<del> updateRanges();
<add> myWriteActionDepth = Math.max(myWriteActionDepth - 1, 0);
<add> if (myWriteActionDepth == 0) {
<add> updateRanges();
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | error: pathspec 'javafx/tools/src/main/java/org/diirt/javafx/tools/HistogramGraphApp.java' did not match any file(s) known to git
| e6766d5d70f88bb379746905839d183c9814aa6f | 1 | ControlSystemStudio/diirt,ControlSystemStudio/diirt,diirt/diirt,ControlSystemStudio/diirt,diirt/diirt,berryma4/diirt,diirt/diirt,berryma4/diirt,berryma4/diirt,diirt/diirt,berryma4/diirt,ControlSystemStudio/diirt | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.diirt.javafx.tools;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import static org.diirt.datasource.formula.ExpressionLanguage.formula;
import static org.diirt.datasource.graphene.ExpressionLanguage.histogramGraphOf;
import org.diirt.datasource.graphene.Graph2DExpression;
import org.diirt.datasource.graphene.HistogramGraph2DExpression;
import org.diirt.graphene.AreaGraph2DRendererUpdate;
/**
*
* @author Mickey
*/
public class HistogramGraphApp extends BaseGraphApp {
private boolean highlightFocusValue;
final private BaseGraphView< AreaGraph2DRendererUpdate > histogramGraphView = new BaseGraphView< AreaGraph2DRendererUpdate >() {
@Override
public Graph2DExpression<AreaGraph2DRendererUpdate> createExpression(String dataFormula) {
HistogramGraph2DExpression plot = histogramGraphOf(formula(dataFormula));
plot.update(plot.newUpdate().highlightFocusValue(highlightFocusValue));
return plot;
}
@Override
protected void onMouseMove(MouseEvent e) {
if ( graph != null ) {
graph.update(graph.newUpdate().focusPixel( (int)e.getX() ));
}
}
};
public boolean isHighlightFocusValue() {
return highlightFocusValue;
}
public void setHighlightFocusValue(boolean highlightFocusValue) {
this.highlightFocusValue = highlightFocusValue;
graph.update(graph.newUpdate().highlightFocusValue(highlightFocusValue));
}
private Graph2DExpression< AreaGraph2DRendererUpdate > graph;
@Override
public BaseGraphView getGraphView() {
return this.histogramGraphView;
}
@Override
public void start( Stage stage ) throws Exception {
super.start( stage );
graph = this.histogramGraphView.graph;
this.addDataFormulae( DataFormulaFactory.fromFormula( this.histogramGraphView , "sim://gaussianWaveform" ) ,
DataFormulaFactory.fromNameAndFormula( this.histogramGraphView , "Noise" , "=histogramOf('sim://noiseWaveform')") ,
DataFormulaFactory.fromFormula( this.histogramGraphView , "=arrayWithBoundaries(arrayOf(1,3,2,4,3,5), range(-10,10))")
);
}
final public static void main( String[] args ) {
launch( args );
}
}
| javafx/tools/src/main/java/org/diirt/javafx/tools/HistogramGraphApp.java | Finish HistogramGraphApp
| javafx/tools/src/main/java/org/diirt/javafx/tools/HistogramGraphApp.java | Finish HistogramGraphApp | <ide><path>avafx/tools/src/main/java/org/diirt/javafx/tools/HistogramGraphApp.java
<add>/*
<add> * To change this license header, choose License Headers in Project Properties.
<add> * To change this template file, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>package org.diirt.javafx.tools;
<add>
<add>import javafx.scene.input.MouseEvent;
<add>import javafx.stage.Stage;
<add>import static org.diirt.datasource.formula.ExpressionLanguage.formula;
<add>import static org.diirt.datasource.graphene.ExpressionLanguage.histogramGraphOf;
<add>import org.diirt.datasource.graphene.Graph2DExpression;
<add>import org.diirt.datasource.graphene.HistogramGraph2DExpression;
<add>import org.diirt.graphene.AreaGraph2DRendererUpdate;
<add>
<add>/**
<add> *
<add> * @author Mickey
<add> */
<add>public class HistogramGraphApp extends BaseGraphApp {
<add>
<add> private boolean highlightFocusValue;
<add>
<add> final private BaseGraphView< AreaGraph2DRendererUpdate > histogramGraphView = new BaseGraphView< AreaGraph2DRendererUpdate >() {
<add>
<add> @Override
<add> public Graph2DExpression<AreaGraph2DRendererUpdate> createExpression(String dataFormula) {
<add> HistogramGraph2DExpression plot = histogramGraphOf(formula(dataFormula));
<add> plot.update(plot.newUpdate().highlightFocusValue(highlightFocusValue));
<add> return plot;
<add> }
<add>
<add> @Override
<add> protected void onMouseMove(MouseEvent e) {
<add> if ( graph != null ) {
<add> graph.update(graph.newUpdate().focusPixel( (int)e.getX() ));
<add> }
<add> }
<add> };
<add>
<add>
<add> public boolean isHighlightFocusValue() {
<add> return highlightFocusValue;
<add> }
<add>
<add> public void setHighlightFocusValue(boolean highlightFocusValue) {
<add> this.highlightFocusValue = highlightFocusValue;
<add> graph.update(graph.newUpdate().highlightFocusValue(highlightFocusValue));
<add> }
<add>
<add> private Graph2DExpression< AreaGraph2DRendererUpdate > graph;
<add>
<add> @Override
<add> public BaseGraphView getGraphView() {
<add> return this.histogramGraphView;
<add> }
<add>
<add> @Override
<add> public void start( Stage stage ) throws Exception {
<add> super.start( stage );
<add> graph = this.histogramGraphView.graph;
<add> this.addDataFormulae( DataFormulaFactory.fromFormula( this.histogramGraphView , "sim://gaussianWaveform" ) ,
<add> DataFormulaFactory.fromNameAndFormula( this.histogramGraphView , "Noise" , "=histogramOf('sim://noiseWaveform')") ,
<add> DataFormulaFactory.fromFormula( this.histogramGraphView , "=arrayWithBoundaries(arrayOf(1,3,2,4,3,5), range(-10,10))")
<add>
<add> );
<add> }
<add>
<add> final public static void main( String[] args ) {
<add> launch( args );
<add> }
<add>} |
|
Java | apache-2.0 | a7641c31bd3dc00888d35f77f0e72382d060e3ad | 0 | DAA233/EasyEcard,SunGoodBoy/EasyEcard | package com.duang.easyecard.Activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.duang.easyecard.R;
import com.duang.easyecard.GlobalData.MyApplication;
import com.duang.easyecard.GlobalData.UrlConstant;
import com.duang.easyecard.Utils.HttpUtil;
import com.duang.easyecard.Utils.HttpUtil.HttpCallbackListener;
import com.duang.easyecard.Utils.ImageUtil;
import com.duang.easyecard.Utils.LogUtil;
import com.duang.easyecard.Utils.ImageUtil.OnLoadImageListener;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SigninActivity extends BaseActivity implements OnClickListener,
OnFocusChangeListener {
private HttpClient httpClient = new DefaultHttpClient();
private Spinner signinTypeSpinner;
private AutoCompleteTextView accountInput;
private EditText passwordInput;
private EditText checkcodeInput;
private TextView accountText;
private TextView hintText;
private Button signinButton;
private ImageView checkcodeImage;
private String signtype; // {"SynSno", "SynCard"}
private String username;
private String password;
private String checkcode;
private List<String> spinnerList = new ArrayList<String>();
private ArrayAdapter<String> spinnerAdapter;
private ArrayAdapter<String> autoCompleteAdapter;
private static String[] autoCompleteStringArray = {"最近登录成功的账号", ""};
private static Map<String, String> rememberedPassword =
new HashMap<String, String>();
private static final int SIGNIN_SUCCESS = 1;
private static final int SIGNIN_FAILED = 0;
private static final int NETWORK_ERROR = 0x404;
private static int DONT_DISPLAY_AGAIN_FLAG = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTitle("登录");
setContentView(R.layout.activity_signin);
initView();
}
public void initView() {
// 实例化控件
signinTypeSpinner = (Spinner) findViewById(R.id.signin_type_spinner);
accountInput = (AutoCompleteTextView)
findViewById(R.id.signin_account_input);
passwordInput = (EditText) findViewById(R.id.signin_password_input);
checkcodeInput = (EditText) findViewById(R.id.signin_checkcode_input);
accountText = (TextView) findViewById(R.id.signin_account_text);
hintText = (TextView) findViewById(R.id.signin_hint_text);
signinButton = (Button) findViewById(R.id.signin_signin_button);
checkcodeImage = (ImageView) findViewById(R.id.signin_checkcode_image);
// 设置Spinner
// 添加列表项
spinnerList.add("学工号");
spinnerList.add("校园卡账号");
// 新建适配器,利用系统内置的layout
spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinnerList);
// 设置下拉菜单样式,利用系统内置的layout
spinnerAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
// 绑定适配器到控件
signinTypeSpinner.setAdapter(spinnerAdapter);
// 设置选择响应事件
signinTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// 选中响应事件
if (position == 0) {
accountText.setText("学 工 号");
accountInput.setHint("请输入学(工)号");
signtype = "SynSno";
hintText.setText("提示:请输入学(工)号");
} else if (position == 1) {
accountText.setText("校园卡号");
accountInput.setHint("请输入校园卡账号");
signtype = "SynCard";
hintText.setText("提示:请输入校园卡账号");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// 什么都没选中
}
});
// 设置账号自动填充的适配器
autoCompleteAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, autoCompleteStringArray);
accountInput.setAdapter(autoCompleteAdapter);
accountInput.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// 选中了自动填充文本,将记住的密码输入
passwordInput.setText(rememberedPassword
.get(autoCompleteStringArray[1]));
}
});
getCheckcodeImage(); // 获取验证码
// 监听EditText的焦点改变事件
accountInput.setOnFocusChangeListener(this);
passwordInput.setOnFocusChangeListener(this);
checkcodeInput.setOnFocusChangeListener(this);
// 监听控件的点击事件
signinButton.setOnClickListener(this);
checkcodeImage.setOnClickListener(this);
}
private void getCheckcodeImage() {
// 获取验证码图片
ImageUtil.onLoadImage(UrlConstant.GET_CHECKCODE_IMG, httpClient,
new OnLoadImageListener() {
@Override
public void OnLoadImage(Bitmap bitmap, String bitmapPath) {
if (bitmap != null) {
checkcodeImage.setImageBitmap(bitmap);
checkcodeInput.setText(null);
}
}
});
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
// 控件焦点的改变事件
switch (v.getId()) {
case R.id.signin_account_input:
if (!hasFocus) {
if (!accountInput.getText().toString().isEmpty()) {
if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
}
}
}
break;
case R.id.signin_password_input:
if (hasFocus) {
if (accountInput.getText().toString().isEmpty()) {
if (signtype.equals("SynSno")) {
hintText.setText("提示:请输入学(工)号");
} else {
hintText.setText("提示:请输入校园卡账号");
}
}
} else {
// 失去焦点
if (!accountInput.getText().toString().isEmpty()) {
if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
}
}
}
break;
case R.id.signin_checkcode_input:
if (hasFocus) {
if (accountInput.getText().toString().isEmpty()) {
if (signtype.equals("SynSno")) {
hintText.setText("提示:请输入学(工)号");
} else {
hintText.setText("提示:请输入校园卡账号");
}
} else if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
} else {
hintText.setText("提示:如果看不清,试试点击图片换一张");
}
}
break;
default:
break;
}
}
@Override
public void onClick(View v) {
// 控件的点击事件
switch (v.getId()) {
// 验证码图片
case R.id.signin_checkcode_image:
getCheckcodeImage();
break;
// 点击登录按钮
case R.id.signin_signin_button:
if (!accountInput.getText().toString().isEmpty()) {
if (!passwordInput.getText().toString().isEmpty()) {
if (!checkcodeInput.getText().toString().isEmpty()) {
// 发送POST请求
sendPostRequest();
} else {
hintText.setText("提示:请输入验证码");
}
} else {
hintText.setText("提示:请输入密码");
}
} else {
hintText.setText("提示:请输入学(工)号");
}
break;
default:
break;
}
}
// 处理从线程中传递出来的消息
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SIGNIN_SUCCESS:
// 登录成功
hintText.setText("提示:登录成功!");
// 传递全局变量http
MyApplication myApp = (MyApplication) getApplication();
myApp.setHttpClient(httpClient);
if (myApp.getHttpClient() != null) {
LogUtil.d("httpClient", "success to spread");
}
// 记录登录成功的账号
autoCompleteStringArray[1] = username;
// 弹出是否记住密码对话框
if (rememberedPassword.isEmpty()) {
// 初次使用此客户端登录
popRememberPasswordDialog();
} else if (!rememberedPassword.containsKey(username)) {
// 切换用户登录
popRememberPasswordDialog();
} else if (DONT_DISPLAY_AGAIN_FLAG == 0) {
popRememberPasswordDialog();
} else {
// 直接跳转到主界面
Intent intent = new Intent(MyApplication.getContext(),
MainActivity.class);
startActivity(intent);
finish(); // 销毁活动
}
break;
case SIGNIN_FAILED:
// 登录出错
String responseString = msg.obj + "";
hintText.setText("提示:" + responseString);
if (responseString.contains("查询密码")) {
passwordInput.setText("");
} else if (responseString.contains("验证码")) {
getCheckcodeImage(); // 刷新验证码
}
break;
case NETWORK_ERROR:
// 网络错误
Toast.makeText(SigninActivity.this, "网络错误",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
private void sendPostRequest() {
// 装填POST数据
List<NameValuePair> params = new ArrayList<NameValuePair>();
checkcode = checkcodeInput.getText().toString();
username = accountInput.getText().toString();
password = passwordInput.getText().toString();
params.add(new BasicNameValuePair("checkcode", checkcode));
params.add(new BasicNameValuePair("IsUsedKeyPad", "False"));
params.add(new BasicNameValuePair("signtype", signtype));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// 发送POST请求
HttpUtil.sendPostRequest(httpClient, UrlConstant.MINI_CHECK_IN, params,
new HttpCallbackListener() {
@Override
public void onFinish(String response) {
// 成功响应
if (response.contains("success")) {
// 发送登录成功的消息
LogUtil.d("response", "success");
Message message = new Message();
message.what = SIGNIN_SUCCESS;
handler.sendMessage(message);
} else {
// 登录发生错误
Message message = new Message();
message.what = SIGNIN_FAILED;
message.obj = response;
handler.sendMessage(message);
}
}
@Override
public void onError(Exception e) {
// 网络错误
Message message = new Message();
message.what = NETWORK_ERROR;
handler.sendMessage(message);
}
});
}
private void popRememberPasswordDialog() {
AlertDialog.Builder dialog = new AlertDialog
.Builder(SigninActivity.this);
String[] dialogItems = {"记住密码", "不再提示"};
dialog.setTitle("提示");
dialog.setMultiChoiceItems(dialogItems, null,
new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
// Item被选中的响应事件
switch (which) {
case 0:
// 选中了“记住密码”
rememberedPassword.put(username, password);
break;
case 1:
// 选中了“不再提示”
DONT_DISPLAY_AGAIN_FLAG = 1;
break;
default:
break;
}
}
});
dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到主界面
Intent intent = new Intent(MyApplication.getContext(),
MainActivity.class);
startActivity(intent);
finish(); // 销毁活动
}
});
dialog.show();
}
}
| src/com/duang/easyecard/Activities/SigninActivity.java | package com.duang.easyecard.Activities;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.duang.easyecard.R;
import com.duang.easyecard.GlobalData.MyApplication;
import com.duang.easyecard.GlobalData.UrlConstant;
import com.duang.easyecard.Utils.HttpUtil;
import com.duang.easyecard.Utils.HttpUtil.HttpCallbackListener;
import com.duang.easyecard.Utils.ImageUtil;
import com.duang.easyecard.Utils.LogUtil;
import com.duang.easyecard.Utils.ImageUtil.OnLoadImageListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SigninActivity extends BaseActivity implements OnClickListener,
OnFocusChangeListener {
private HttpClient httpClient = new DefaultHttpClient();
private Spinner signinTypeSpinner;
private AutoCompleteTextView accountInput;
private EditText passwordInput;
private EditText checkcodeInput;
private TextView accountText;
private TextView hintText;
private Button signinButton;
private ImageView checkcodeImage;
private String signtype; // {"SynSno", "SynCard"}
private String username;
private String password;
private String checkcode;
private List<String> spinnerList = new ArrayList<String>();
private ArrayAdapter<String> spinnerAdapter;
private ArrayAdapter<String> autoCompleteAdapter;
private static String[] autoCompleteStringArray = {"曾经登录成功的账号", ""};
private static final int SIGNIN_SUCCESS = 1;
private static final int SIGNIN_FAILED = 0;
private static final int NETWORK_ERROR = 0x404;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTitle("登录");
setContentView(R.layout.activity_signin);
initView();
}
public void initView() {
// 实例化控件
signinTypeSpinner = (Spinner) findViewById(R.id.signin_type_spinner);
accountInput = (AutoCompleteTextView)
findViewById(R.id.signin_account_input);
passwordInput = (EditText) findViewById(R.id.signin_password_input);
checkcodeInput = (EditText) findViewById(R.id.signin_checkcode_input);
accountText = (TextView) findViewById(R.id.signin_account_text);
hintText = (TextView) findViewById(R.id.signin_hint_text);
signinButton = (Button) findViewById(R.id.signin_signin_button);
checkcodeImage = (ImageView) findViewById(R.id.signin_checkcode_image);
// 设置Spinner
// 添加列表项
spinnerList.add("学工号");
spinnerList.add("校园卡账号");
// 新建适配器,利用系统内置的layout
spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinnerList);
// 设置下拉菜单样式,利用系统内置的layout
spinnerAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
// 绑定适配器到控件
signinTypeSpinner.setAdapter(spinnerAdapter);
// 设置选择响应事件
signinTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// 选中响应事件
if (position == 0) {
accountText.setText("学 工 号");
accountInput.setHint("请输入学(工)号");
signtype = "SynSno";
hintText.setText("提示:请输入学(工)号");
} else if (position == 1) {
accountText.setText("校园卡号");
accountInput.setHint("请输入校园卡账号");
signtype = "SynCard";
hintText.setText("提示:请输入校园卡账号");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// 什么都没选中
}
});
// 设置帐号自动填充的适配器
autoCompleteAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, autoCompleteStringArray);
accountInput.setAdapter(autoCompleteAdapter);
getCheckcodeImage(); // 获取验证码
// 监听EditText的焦点改变事件
accountInput.setOnFocusChangeListener(this);
passwordInput.setOnFocusChangeListener(this);
checkcodeInput.setOnFocusChangeListener(this);
// 监听控件的点击事件
signinButton.setOnClickListener(this);
checkcodeImage.setOnClickListener(this);
}
private void getCheckcodeImage() {
// 获取验证码图片
ImageUtil.onLoadImage(UrlConstant.GET_CHECKCODE_IMG, httpClient,
new OnLoadImageListener() {
@Override
public void OnLoadImage(Bitmap bitmap, String bitmapPath) {
if (bitmap != null) {
checkcodeImage.setImageBitmap(bitmap);
checkcodeInput.setText(null);
}
}
});
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
// 控件焦点的改变事件
switch (v.getId()) {
case R.id.signin_account_input:
if (!hasFocus) {
if (!accountInput.getText().toString().isEmpty()) {
if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
}
}
}
break;
case R.id.signin_password_input:
if (hasFocus) {
if (accountInput.getText().toString().isEmpty()) {
if (signtype.equals("SynSno")) {
hintText.setText("提示:请输入学(工)号");
} else {
hintText.setText("提示:请输入校园卡账号");
}
}
} else {
// 失去焦点
if (!accountInput.getText().toString().isEmpty()) {
if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
}
}
}
break;
case R.id.signin_checkcode_input:
if (hasFocus) {
if (accountInput.getText().toString().isEmpty()) {
if (signtype.equals("SynSno")) {
hintText.setText("提示:请输入学(工)号");
} else {
hintText.setText("提示:请输入校园卡账号");
}
} else if (passwordInput.getText().toString().isEmpty()) {
hintText.setText("提示:请输入密码");
} else {
hintText.setText("提示:如果看不清,试试点击图片换一张");
}
}
break;
default:
break;
}
}
@Override
public void onClick(View v) {
// 控件的点击事件
switch (v.getId()) {
// 验证码图片
case R.id.signin_checkcode_image:
getCheckcodeImage();
break;
// 点击登录按钮
case R.id.signin_signin_button:
if (!accountInput.getText().toString().isEmpty()) {
if (!passwordInput.getText().toString().isEmpty()) {
if (!checkcodeInput.getText().toString().isEmpty()) {
// 发送POST请求
sendPostRequest();
} else {
hintText.setText("提示:请输入验证码");
}
} else {
hintText.setText("提示:请输入密码");
}
} else {
hintText.setText("提示:请输入学(工)号");
}
break;
default:
break;
}
}
// 处理从线程中传递出来的消息
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SIGNIN_SUCCESS:
// 登录成功
hintText.setText("提示:登录成功!");
// 传递全局变量http
MyApplication myApp = (MyApplication) getApplication();
myApp.setHttpClient(httpClient);
if (myApp.getHttpClient() != null) {
LogUtil.d("httpClient", "success to spread");
}
// 进入主功能界面
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
finish(); // 销毁当前活动
break;
case SIGNIN_FAILED:
// 登录出错
String responseString = msg.obj + "";
hintText.setText("提示:" + responseString);
if (responseString.contains("查询密码")) {
passwordInput.setText("");
} else if (responseString.contains("验证码")) {
getCheckcodeImage(); // 刷新验证码
}
break;
case NETWORK_ERROR:
// 网络错误
Toast.makeText(SigninActivity.this, "网络错误",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
private void sendPostRequest() {
// 装填POST数据
List<NameValuePair> params = new ArrayList<NameValuePair>();
checkcode = checkcodeInput.getText().toString();
username = accountInput.getText().toString();
password = passwordInput.getText().toString();
params.add(new BasicNameValuePair("checkcode", checkcode));
params.add(new BasicNameValuePair("IsUsedKeyPad", "False"));
params.add(new BasicNameValuePair("signtype", signtype));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// 发送POST请求
HttpUtil.sendPostRequest(httpClient, UrlConstant.MINI_CHECK_IN, params,
new HttpCallbackListener() {
@Override
public void onFinish(String response) {
// 成功响应
if (response.contains("success")) {
// 记录登录成功的帐号
autoCompleteStringArray[1] = username;
// 发送登录成功的消息
LogUtil.d("response", "success");
Message message = new Message();
message.what = SIGNIN_SUCCESS;
handler.sendMessage(message);
} else {
// 登录发生错误
Message message = new Message();
message.what = SIGNIN_FAILED;
message.obj = response;
handler.sendMessage(message);
}
}
@Override
public void onError(Exception e) {
// 网络错误
Message message = new Message();
message.what = NETWORK_ERROR;
handler.sendMessage(message);
}
});
}
}
| Add RememberPassword function to SigninActivity.
| src/com/duang/easyecard/Activities/SigninActivity.java | Add RememberPassword function to SigninActivity. | <ide><path>rc/com/duang/easyecard/Activities/SigninActivity.java
<ide> package com.duang.easyecard.Activities;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.List;
<add>import java.util.Map;
<ide>
<ide> import org.apache.http.NameValuePair;
<ide> import org.apache.http.client.HttpClient;
<ide> import com.duang.easyecard.Utils.LogUtil;
<ide> import com.duang.easyecard.Utils.ImageUtil.OnLoadImageListener;
<ide>
<add>import android.app.AlertDialog;
<add>import android.content.DialogInterface;
<add>import android.content.DialogInterface.OnMultiChoiceClickListener;
<ide> import android.content.Intent;
<ide> import android.graphics.Bitmap;
<ide> import android.os.Bundle;
<ide> import android.view.View.OnClickListener;
<ide> import android.view.View.OnFocusChangeListener;
<ide> import android.widget.AdapterView;
<add>import android.widget.AdapterView.OnItemClickListener;
<ide> import android.widget.AdapterView.OnItemSelectedListener;
<ide> import android.widget.ArrayAdapter;
<ide> import android.widget.AutoCompleteTextView;
<ide> private List<String> spinnerList = new ArrayList<String>();
<ide> private ArrayAdapter<String> spinnerAdapter;
<ide> private ArrayAdapter<String> autoCompleteAdapter;
<del> private static String[] autoCompleteStringArray = {"曾经登录成功的账号", ""};
<add> private static String[] autoCompleteStringArray = {"最近登录成功的账号", ""};
<add> private static Map<String, String> rememberedPassword =
<add> new HashMap<String, String>();
<ide>
<ide> private static final int SIGNIN_SUCCESS = 1;
<ide> private static final int SIGNIN_FAILED = 0;
<ide> private static final int NETWORK_ERROR = 0x404;
<add>
<add> private static int DONT_DISPLAY_AGAIN_FLAG = 0;
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> }
<ide> });
<ide>
<del> // 设置帐号自动填充的适配器
<add> // 设置账号自动填充的适配器
<ide> autoCompleteAdapter = new ArrayAdapter<String>(this,
<ide> android.R.layout.simple_list_item_1, autoCompleteStringArray);
<ide> accountInput.setAdapter(autoCompleteAdapter);
<add> accountInput.setOnItemClickListener(new OnItemClickListener() {
<add> @Override
<add> public void onItemClick(AdapterView<?> arg0, View arg1,
<add> int arg2, long arg3) {
<add> // 选中了自动填充文本,将记住的密码输入
<add> passwordInput.setText(rememberedPassword
<add> .get(autoCompleteStringArray[1]));
<add> }
<add> });
<ide>
<ide> getCheckcodeImage(); // 获取验证码
<ide>
<ide> if (myApp.getHttpClient() != null) {
<ide> LogUtil.d("httpClient", "success to spread");
<ide> }
<del> // 进入主功能界面
<del> Intent intent = new Intent(getApplicationContext(),
<del> MainActivity.class);
<del> intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
<del> getApplicationContext().startActivity(intent);
<del> finish(); // 销毁当前活动
<add> // 记录登录成功的账号
<add> autoCompleteStringArray[1] = username;
<add> // 弹出是否记住密码对话框
<add> if (rememberedPassword.isEmpty()) {
<add> // 初次使用此客户端登录
<add> popRememberPasswordDialog();
<add> } else if (!rememberedPassword.containsKey(username)) {
<add> // 切换用户登录
<add> popRememberPasswordDialog();
<add> } else if (DONT_DISPLAY_AGAIN_FLAG == 0) {
<add> popRememberPasswordDialog();
<add> } else {
<add> // 直接跳转到主界面
<add> Intent intent = new Intent(MyApplication.getContext(),
<add> MainActivity.class);
<add> startActivity(intent);
<add> finish(); // 销毁活动
<add> }
<ide> break;
<ide> case SIGNIN_FAILED:
<ide> // 登录出错
<ide> public void onFinish(String response) {
<ide> // 成功响应
<ide> if (response.contains("success")) {
<del> // 记录登录成功的帐号
<del> autoCompleteStringArray[1] = username;
<ide> // 发送登录成功的消息
<ide> LogUtil.d("response", "success");
<ide> Message message = new Message();
<ide> }
<ide> });
<ide> }
<add>
<add> private void popRememberPasswordDialog() {
<add> AlertDialog.Builder dialog = new AlertDialog
<add> .Builder(SigninActivity.this);
<add> String[] dialogItems = {"记住密码", "不再提示"};
<add> dialog.setTitle("提示");
<add> dialog.setMultiChoiceItems(dialogItems, null,
<add> new OnMultiChoiceClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialog,
<add> int which, boolean isChecked) {
<add> // Item被选中的响应事件
<add> switch (which) {
<add> case 0:
<add> // 选中了“记住密码”
<add> rememberedPassword.put(username, password);
<add> break;
<add> case 1:
<add> // 选中了“不再提示”
<add> DONT_DISPLAY_AGAIN_FLAG = 1;
<add> break;
<add> default:
<add> break;
<add> }
<add> }
<add> });
<add> dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialog, int which) {
<add> // 跳转到主界面
<add> Intent intent = new Intent(MyApplication.getContext(),
<add> MainActivity.class);
<add> startActivity(intent);
<add> finish(); // 销毁活动
<add> }
<add> });
<add> dialog.show();
<add> }
<ide> } |
|
Java | mit | 59ee9a254399ffba755cbc10574a36299369a545 | 0 | NyaaCat/PlayTimeTracker | package cat.nyaa.playtimetracker;
import cat.nyaa.nyaacore.utils.InventoryUtils;
import cat.nyaa.nyaacore.utils.ItemStackUtils;
import cat.nyaa.playtimetracker.Utils.TaskUtils;
import cat.nyaa.playtimetracker.Utils.TimeUtils;
import cat.nyaa.playtimetracker.config.PTTConfiguration;
import cat.nyaa.playtimetracker.config.data.MissionData;
import cat.nyaa.playtimetracker.db.connection.CompletedMissionConnection;
import cat.nyaa.playtimetracker.db.model.CompletedMissionDbModel;
import cat.nyaa.playtimetracker.db.model.TimeTrackerDbModel;
import com.udojava.evalex.Expression;
import me.clip.placeholderapi.PlaceholderAPI;
import net.ess3.api.IEssentials;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
public class PlayerMissionManager {
private final PlayTimeTracker plugin;
@Nullable
private static PlayerMissionManager instance;
private final List<AwaitingReward> awaitingRewardList = new ArrayList<>();
private final CompletedMissionConnection completedMissionConnection;
private final PTTConfiguration pttConfiguration;
private final TimeRecordManager timeRecordManager;
private int tickNum;
public PlayerMissionManager(PlayTimeTracker playTimeTracker, PTTConfiguration pttConfiguration, TimeRecordManager timeRecordManager, CompletedMissionConnection completedMissionConnection) {
instance = this;
this.plugin = playTimeTracker;
this.pttConfiguration = pttConfiguration;
this.completedMissionConnection = completedMissionConnection;
this.timeRecordManager = timeRecordManager;
}
public PlayTimeTracker getPlugin() {
return plugin;
}
@Nullable
public static PlayerMissionManager getInstance() {
return instance;
}
public void getMissionReward(Player player, String mission) {
Map<String, MissionData> missionDataMap = getMissionDataMap();
if (!missionDataMap.containsKey(mission)) return;
I18n.send(player, "message.mission.get_reward", mission);
MissionData missionData = missionDataMap.get(mission);
//item
try {
if (missionData.rewardItemSteakBase64 != null && !missionData.rewardItemSteakBase64.isEmpty()) {
ItemStack itemStack = ItemStackUtils.itemFromBase64(missionData.rewardItemSteakBase64);
if (InventoryUtils.hasEnoughSpace(player.getInventory(), itemStack)) {
InventoryUtils.addItem(player, itemStack);
} else {
player.getWorld().dropItem(player.getLocation(), itemStack);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//command
if (missionData.rewardCommandList != null)
for (String command : missionData.rewardCommandList) {
if (command != null && !command.isEmpty())
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), PlaceholderAPI.setPlaceholders(player, command));
}
}
public boolean completeMission(@NotNull Player player, String mission) {
if (completeMissionNoReward(player.getUniqueId(), mission)) {
getMissionReward(player, mission);
return true;
}
return false;
}
public boolean completeMissionNoReward(UUID playerId, String mission) {
boolean write2db = removeAwaitingReward(playerId, mission);
if (write2db) {
completedMissionConnection.WriteMissionCompleted(playerId, mission, TimeUtils.getUnixTimeStampNow());
}
return write2db;
}
// public Map<String, MissionData> getMissionDataMap() {
// Map<String, MissionData> missionDataMap = new HashMap<>();
// getMissionDataList().forEach(missionData -> missionDataMap.put(missionData.missionName, missionData));
// return missionDataMap;
// }
public void checkAwaitingRewardList() {
Map<String, MissionData> missionDataMap = getMissionDataMap();
new ArrayList<>(awaitingRewardList).forEach(
awaitingReward -> {
if (!missionDataMap.containsKey(awaitingReward.mission)) return;
if (missionDataMap.get(awaitingReward.mission).timeoutMS < 0) return;
if ((TimeUtils.getUnixTimeStampNow() - awaitingReward.time) >= missionDataMap.get(awaitingReward.mission).timeoutMS) {
completeMissionNoReward(awaitingReward.playerId, awaitingReward.mission);
}
}
);
}
public void checkPlayerMission(@NotNull Player player) {
if (!player.isOnline()) return;
TimeTrackerDbModel trackerDbModel = timeRecordManager.getPlayerTimeTrackerDbModel(player);
if (trackerDbModel == null) return;
//this.checkAndResetPlayerCompletedMission(player);
getMissionDataMap().forEach(
(missionName, missionData) -> {
CompletedMissionDbModel completedMissionDbModel = completedMissionConnection.getPlayerCompletedMission(player.getUniqueId(), missionName);
if (completedMissionDbModel != null) {
return;
}
//awaitingReward
AwaitingReward awaitingReward = getAwaitingReward(player, missionName);
if (awaitingReward != null) {
return; // after checkAwaitingRewardList
}
//group
if (missionData.group != null && !missionData.group.isEmpty()) {
if (getPlugin().getEssentialsPlugin() == null) return;
boolean inGroup = false;
for (String s : missionData.group) {
if (((IEssentials) getPlugin().getEssentialsPlugin()).getUser(player).inGroup(s)) {
inGroup = true;
break;
}
}
if (!inGroup) return;
}
//
if (missionData.expression == null || missionData.expression.isEmpty()) return;
BigDecimal lastSeen = new BigDecimal(trackerDbModel.getLastSeen());
BigDecimal dailyTime = new BigDecimal(trackerDbModel.getDailyTime());
BigDecimal weeklyTime = new BigDecimal(trackerDbModel.getWeeklyTime());
BigDecimal monthlyTime = new BigDecimal(trackerDbModel.getMonthlyTime());
BigDecimal totalTime = new BigDecimal(trackerDbModel.getTotalTime());
BigDecimal result;
try {
result = new com.udojava.evalex.Expression(missionData.expression)
.with("lastSeen", lastSeen)
.with("dailyTime", dailyTime)
.with("weeklyTime", weeklyTime)
.with("monthlyTime", monthlyTime)
.with("totalTime", totalTime)
.eval();
} catch (Expression.ExpressionException e) {
e.printStackTrace();
return;
}
if (result.doubleValue() <= 0) {
return;
}
this.putAwaitingReward(player, missionName, missionData.notify);
if (missionData.autoGive) {
completeMission(player, missionName);
}
}
);
}
public Set<String> getAwaitingMissionNameSet(Player player) {
return awaitingRewardList.stream()
.filter(awaitingReward -> awaitingReward.playerId == player.getUniqueId())
.map(awaitingReward -> awaitingReward.mission).collect(Collectors.toSet());
}
@Nullable
private AwaitingReward getAwaitingReward(Player player, String missionName) {
for (AwaitingReward awaitingReward : awaitingRewardList) {
if (awaitingReward.playerId == player.getUniqueId() && awaitingReward.mission.equals(missionName)) {
return awaitingReward;
}
}
return null;
}
private boolean removeAwaitingReward(UUID playerId, String missionName) {
AtomicBoolean result = new AtomicBoolean(false);
awaitingRewardList.removeIf(awaitingReward -> {
if (awaitingReward.playerId == playerId
&& awaitingReward.mission.equals(missionName)) {
result.set(true);
return true;
}
return false;
}
);
return result.get();
}
private void putAwaitingReward(@NotNull Player player, String missionName, boolean notify) {
removeAwaitingReward(player.getUniqueId(), missionName);
awaitingRewardList.add(new AwaitingReward(player.getUniqueId(), missionName, TimeUtils.getUnixTimeStampNow(), notify));
}
private Map<String, MissionData> getMissionDataMap() {
return pttConfiguration.missionConfig.missions;
}
public void missionCheckTick() {
this.tickNum++;
checkAwaitingRewardList();
Bukkit.getOnlinePlayers().forEach(player ->
TaskUtils.mod64TickToRun(this.tickNum, player.getUniqueId(), () -> checkPlayerMission(player))
);
}
public void notifyAcquire() {
awaitingRewardList.forEach(awaitingReward -> {
if (awaitingReward.isNotify) {
Player player = Bukkit.getPlayer(awaitingReward.playerId);
if (player != null) {
String command = PlaceholderAPI.setPlaceholders(player, I18n.format("message.mission.notify.command", awaitingReward.mission));
String msg = PlaceholderAPI.setPlaceholders(player, I18n.format("message.mission.notify.msg", awaitingReward.mission));
BaseComponent[] commandComponent = new ComponentBuilder()
.append(msg)
.append(command)
.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command))
.create();
player.spigot().sendMessage(new TextComponent(commandComponent));
}
}
});
}
public void onDailyReset(UUID playerId) {
resetMission(true, false, false, playerId);
}
public void onWeeklyReset(UUID playerId) {
resetMission(false, true, false, playerId);
}
public void onMonthlyReset(UUID playerId) {
resetMission(false, false, true, playerId);
}
private void resetMission(boolean daily, boolean weekly, boolean monthly, UUID playerId) {
if (!daily && !weekly && !monthly) return;
getMissionDataMap().forEach(
(missionName, missionData) -> {
if ((missionData.resetDaily && daily) || (missionData.resetWeekly && weekly) || (missionData.resetMonthly && monthly)) {
this.completedMissionConnection.resetAllMissionData(missionName, playerId);
}
}
);
}
public record AwaitingReward(UUID playerId, String mission, long time, boolean isNotify) {
}
}
| src/main/java/cat/nyaa/playtimetracker/PlayerMissionManager.java | package cat.nyaa.playtimetracker;
import cat.nyaa.nyaacore.utils.InventoryUtils;
import cat.nyaa.nyaacore.utils.ItemStackUtils;
import cat.nyaa.playtimetracker.Utils.TaskUtils;
import cat.nyaa.playtimetracker.Utils.TimeUtils;
import cat.nyaa.playtimetracker.config.PTTConfiguration;
import cat.nyaa.playtimetracker.config.data.MissionData;
import cat.nyaa.playtimetracker.db.connection.CompletedMissionConnection;
import cat.nyaa.playtimetracker.db.model.CompletedMissionDbModel;
import cat.nyaa.playtimetracker.db.model.TimeTrackerDbModel;
import com.udojava.evalex.Expression;
import me.clip.placeholderapi.PlaceholderAPI;
import net.ess3.api.IEssentials;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
public class PlayerMissionManager {
private final PlayTimeTracker plugin;
@Nullable
private static PlayerMissionManager instance;
private final List<AwaitingReward> awaitingRewardList = new ArrayList<>();
private final CompletedMissionConnection completedMissionConnection;
private final PTTConfiguration pttConfiguration;
private final TimeRecordManager timeRecordManager;
private int tickNum;
public PlayerMissionManager(PlayTimeTracker playTimeTracker, PTTConfiguration pttConfiguration, TimeRecordManager timeRecordManager, CompletedMissionConnection completedMissionConnection) {
instance = this;
this.plugin = playTimeTracker;
this.pttConfiguration = pttConfiguration;
this.completedMissionConnection = completedMissionConnection;
this.timeRecordManager = timeRecordManager;
}
public PlayTimeTracker getPlugin() {
return plugin;
}
@Nullable
public static PlayerMissionManager getInstance() {
return instance;
}
public void getMissionReward(Player player, String mission) {
Map<String, MissionData> missionDataMap = getMissionDataMap();
if (!missionDataMap.containsKey(mission)) return;
MissionData missionData = missionDataMap.get(mission);
//item
try {
if (missionData.rewardItemSteakBase64 != null && !missionData.rewardItemSteakBase64.isEmpty()) {
ItemStack itemStack = ItemStackUtils.itemFromBase64(missionData.rewardItemSteakBase64);
if (InventoryUtils.hasEnoughSpace(player.getInventory(), itemStack)) {
InventoryUtils.addItem(player, itemStack);
} else {
player.getWorld().dropItem(player.getLocation(), itemStack);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//command
if (missionData.rewardCommandList != null)
for (String command : missionData.rewardCommandList) {
if (command != null && !command.isEmpty())
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), PlaceholderAPI.setPlaceholders(player, command));
}
}
public void completeMission(@NotNull Player player, String mission) {
if (completeMissionNoReward(player.getUniqueId(), mission)) {
getMissionReward(player, mission);
}
}
public boolean completeMissionNoReward(UUID playerId, String mission) {
boolean write2db = removeAwaitingReward(playerId, mission);
if (write2db) {
completedMissionConnection.WriteMissionCompleted(playerId, mission, TimeUtils.getUnixTimeStampNow());
}
return write2db;
}
// public Map<String, MissionData> getMissionDataMap() {
// Map<String, MissionData> missionDataMap = new HashMap<>();
// getMissionDataList().forEach(missionData -> missionDataMap.put(missionData.missionName, missionData));
// return missionDataMap;
// }
public void checkAwaitingRewardList() {
Map<String, MissionData> missionDataMap = getMissionDataMap();
new ArrayList<>(awaitingRewardList).forEach(
awaitingReward -> {
if (!missionDataMap.containsKey(awaitingReward.mission)) return;
if (missionDataMap.get(awaitingReward.mission).timeoutMS < 0) return;
if ((TimeUtils.getUnixTimeStampNow() - awaitingReward.time) >= missionDataMap.get(awaitingReward.mission).timeoutMS) {
completeMissionNoReward(awaitingReward.playerId, awaitingReward.mission);
}
}
);
}
public void checkPlayerMission(@NotNull Player player) {
if (!player.isOnline()) return;
TimeTrackerDbModel trackerDbModel = timeRecordManager.getPlayerTimeTrackerDbModel(player);
if (trackerDbModel == null) return;
//this.checkAndResetPlayerCompletedMission(player);
getMissionDataMap().forEach(
(missionName, missionData) -> {
CompletedMissionDbModel completedMissionDbModel = completedMissionConnection.getPlayerCompletedMission(player.getUniqueId(), missionName);
if (completedMissionDbModel != null) {
return;
}
//awaitingReward
AwaitingReward awaitingReward = getAwaitingReward(player, missionName);
if (awaitingReward != null) {
return; // after checkAwaitingRewardList
}
//group
if (missionData.group != null && !missionData.group.isEmpty()) {
if (getPlugin().getEssentialsPlugin() == null) return;
boolean inGroup = false;
for (String s : missionData.group) {
if (((IEssentials) getPlugin().getEssentialsPlugin()).getUser(player).inGroup(s)) {
inGroup = true;
break;
}
}
if (!inGroup) return;
}
//
if (missionData.expression == null || missionData.expression.isEmpty()) return;
BigDecimal lastSeen = new BigDecimal(trackerDbModel.getLastSeen());
BigDecimal dailyTime = new BigDecimal(trackerDbModel.getDailyTime());
BigDecimal weeklyTime = new BigDecimal(trackerDbModel.getWeeklyTime());
BigDecimal monthlyTime = new BigDecimal(trackerDbModel.getMonthlyTime());
BigDecimal totalTime = new BigDecimal(trackerDbModel.getTotalTime());
BigDecimal result;
try {
result = new com.udojava.evalex.Expression(missionData.expression)
.with("lastSeen", lastSeen)
.with("dailyTime", dailyTime)
.with("weeklyTime", weeklyTime)
.with("monthlyTime", monthlyTime)
.with("totalTime", totalTime)
.eval();
} catch (Expression.ExpressionException e) {
e.printStackTrace();
return;
}
if (result.doubleValue() <= 0) {
return;
}
this.putAwaitingReward(player, missionName, missionData.notify);
if (missionData.autoGive) {
completeMission(player, missionName);
}
}
);
}
@Nullable
private AwaitingReward getAwaitingReward(Player player, String missionName) {
for (AwaitingReward awaitingReward : awaitingRewardList) {
if (awaitingReward.playerId == player.getUniqueId() && awaitingReward.mission.equals(missionName)) {
return awaitingReward;
}
}
return null;
}
private boolean removeAwaitingReward(UUID playerId, String missionName) {
AtomicBoolean result = new AtomicBoolean(false);
awaitingRewardList.removeIf(awaitingReward -> {
if (awaitingReward.playerId == playerId
&& awaitingReward.mission.equals(missionName)) {
result.set(true);
return true;
}
return false;
}
);
return result.get();
}
private void putAwaitingReward(@NotNull Player player, String missionName, boolean notify) {
removeAwaitingReward(player.getUniqueId(), missionName);
awaitingRewardList.add(new AwaitingReward(player.getUniqueId(), missionName, TimeUtils.getUnixTimeStampNow(), notify));
}
private Map<String, MissionData> getMissionDataMap() {
return pttConfiguration.missionConfig.missions;
}
public void missionCheckTick() {
this.tickNum++;
checkAwaitingRewardList();
Bukkit.getOnlinePlayers().forEach(player ->
TaskUtils.mod64TickToRun(this.tickNum, player.getUniqueId(), () -> checkPlayerMission(player))
);
}
public void notifyAcquire() {
awaitingRewardList.forEach(awaitingReward -> {
if (awaitingReward.isNotify) {
Player player = Bukkit.getPlayer(awaitingReward.playerId);
if (player != null) {
String command = PlaceholderAPI.setPlaceholders(player, I18n.format("message.mission.notify.command", awaitingReward.mission));
String msg = PlaceholderAPI.setPlaceholders(player, I18n.format("message.mission.notify.msg", awaitingReward.mission));
BaseComponent[] commandComponent = new ComponentBuilder()
.append(msg)
.append(command)
.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command))
.create();
player.spigot().sendMessage(new TextComponent(commandComponent));
}
}
});
}
public void onDailyReset(UUID playerId) {
resetMission(true, false, false, playerId);
}
public void onWeeklyReset(UUID playerId) {
resetMission(false, true, false, playerId);
}
public void onMonthlyReset(UUID playerId) {
resetMission(false, false, true, playerId);
}
private void resetMission(boolean daily, boolean weekly, boolean monthly, UUID playerId) {
if (!daily && !weekly && !monthly) return;
getMissionDataMap().forEach(
(missionName, missionData) -> {
if ((missionData.resetDaily && daily) || (missionData.resetWeekly && weekly) || (missionData.resetMonthly && monthly)) {
this.completedMissionConnection.resetAllMissionData(missionName, playerId);
}
}
);
}
public record AwaitingReward(UUID playerId, String mission, long time, boolean isNotify) {
}
}
| mission reward message
| src/main/java/cat/nyaa/playtimetracker/PlayerMissionManager.java | mission reward message | <ide><path>rc/main/java/cat/nyaa/playtimetracker/PlayerMissionManager.java
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<ide> import java.math.BigDecimal;
<del>import java.util.ArrayList;
<del>import java.util.List;
<del>import java.util.Map;
<del>import java.util.UUID;
<add>import java.util.*;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.stream.Collectors;
<ide>
<ide> public class PlayerMissionManager {
<ide> private final PlayTimeTracker plugin;
<ide> public void getMissionReward(Player player, String mission) {
<ide> Map<String, MissionData> missionDataMap = getMissionDataMap();
<ide> if (!missionDataMap.containsKey(mission)) return;
<add> I18n.send(player, "message.mission.get_reward", mission);
<ide> MissionData missionData = missionDataMap.get(mission);
<ide> //item
<ide> try {
<ide> }
<ide> }
<ide>
<del> public void completeMission(@NotNull Player player, String mission) {
<add> public boolean completeMission(@NotNull Player player, String mission) {
<ide> if (completeMissionNoReward(player.getUniqueId(), mission)) {
<ide> getMissionReward(player, mission);
<del> }
<add> return true;
<add> }
<add> return false;
<ide> }
<ide>
<ide> public boolean completeMissionNoReward(UUID playerId, String mission) {
<ide> );
<ide> }
<ide>
<add> public Set<String> getAwaitingMissionNameSet(Player player) {
<add> return awaitingRewardList.stream()
<add> .filter(awaitingReward -> awaitingReward.playerId == player.getUniqueId())
<add> .map(awaitingReward -> awaitingReward.mission).collect(Collectors.toSet());
<add> }
<ide>
<ide> @Nullable
<ide> private AwaitingReward getAwaitingReward(Player player, String missionName) { |
|
Java | mit | cf56d532e57dca045ac5703f0e8d26df989fd5af | 0 | disconsented/MPC | /*The MIT License (MIT)
Copyright (c) 2015 Disconsented, James Kerr
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 com.disconsented.monolithicPackChecker;
import java.util.ArrayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Logging {
public static Logger logger = LogManager.getLogger("MPC");
private static ArrayList<String> miscInfo = new ArrayList<String>();
public static void info(Object info) {
logger.info(info);
}
public static void error(Object error) {
logger.error(error);
}
public static void warn(Object warn){
logger.warn(warn);
}
public static void addMiscInfo(String e){
miscInfo.add(e);
}
public static void flushMiscInfo(){
for (String e : miscInfo){
info(e);
}
miscInfo.clear();
}
public static void genericWarning(Exception e){
Logging.warn("An unhandled exception has occured please report this");
Logging.warn(e.getLocalizedMessage());
}
public static void testFail(int i){
Logging.error("Test "+i+" has failed ("+Checks.checkDescriptions[i-1]+")");
}
public static void testPass(int i){
Logging.info("Test "+i+" has passed ("+Checks.checkDescriptions[i-1]+")");
}
}
| src/main/java/com/disconsented/monolithicPackChecker/Logging.java | /*The MIT License (MIT)
Copyright (c) 2015 Disconsented, James Kerr
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 com.disconsented.monolithicPackChecker;
import java.util.ArrayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Logging {
public static Logger logger = LogManager.getLogger("MPC");
private static ArrayList<String> miscInfo = new ArrayList<String>();
public static void info(Object info) {
logger.info(info);
}
public static void error(Object error) {
logger.error(error);
}
public static void warn(Object warn){
logger.warn(warn);
}
public static void addMiscInfo(String e){
miscInfo.add(e);
}
public static void flushMiscInfo(){
for (String e : miscInfo){
info(e);
}
miscInfo.clear();
}
public static void genericWarning(Exception e){
Logging.warn("An unhandled exception has occured please report this");
Logging.warn(e.getLocalizedMessage());
}
public static void testFail(int i){
Logging.error("Test "+i+"has failed ("+Checks.checkDescriptions[i-1]+")");
}
public static void testPass(int i){
Logging.info("Test "+i+"has passed ("+Checks.checkDescriptions[i-1]+")");
}
}
| Formatting adjustment
| src/main/java/com/disconsented/monolithicPackChecker/Logging.java | Formatting adjustment | <ide><path>rc/main/java/com/disconsented/monolithicPackChecker/Logging.java
<ide> public static void info(Object info) {
<ide> logger.info(info);
<ide> }
<del>
<add>
<ide> public static void error(Object error) {
<ide> logger.error(error);
<ide> }
<ide> }
<ide>
<ide> public static void testFail(int i){
<del> Logging.error("Test "+i+"has failed ("+Checks.checkDescriptions[i-1]+")");
<add> Logging.error("Test "+i+" has failed ("+Checks.checkDescriptions[i-1]+")");
<ide> }
<ide>
<ide> public static void testPass(int i){
<del> Logging.info("Test "+i+"has passed ("+Checks.checkDescriptions[i-1]+")");
<add> Logging.info("Test "+i+" has passed ("+Checks.checkDescriptions[i-1]+")");
<ide> }
<ide> } |
|
Java | apache-2.0 | 674d102c1860664722d861cd07e6d62e729b7062 | 0 | realityforge/arez,realityforge/arez,realityforge/arez | package arez;
import javax.annotation.Nonnull;
/**
* Flags that can be passed when creating observers that determine the configuration of the observer.
* The class also contains constants and methods used to extract runtime state from Observers.
*/
public final class Flags
{
/**
* Flag indicating that the Observer is allowed to observe {@link ComputedValue} instances with a lower priority.
*/
public static final int OBSERVE_LOWER_PRIORITY_DEPENDENCIES = 1 << 30;
/**
* Indicates that the an action can be created from within the Observers observed function.
*/
public static final int NESTED_ACTIONS_ALLOWED = 1 << 29;
/**
* Indicates that the an action must not be created from within the Observers observed function.
*/
public static final int NESTED_ACTIONS_DISALLOWED = 1 << 28;
/**
* Mask to extract "NESTED_ACTIONS" option so can derive default value if required.
*/
private static final int NESTED_ACTIONS_MASK = NESTED_ACTIONS_ALLOWED | NESTED_ACTIONS_DISALLOWED;
/**
* Flag set if the application code can invoke {@link Observer#reportStale()} or {@link ComputedValue#reportPossiblyChanged()} to indicate non-arez dependency has changed.
*/
public static final int NON_AREZ_DEPENDENCIES = 1 << 27;
/**
* Flag set set if the application code can not invoke {@link Observer#reportStale()} or {@link ComputedValue#reportPossiblyChanged()} to indicate dependency has changed.
*/
public static final int AREZ_DEPENDENCIES_ONLY = 1 << 26;
/**
* Mask used to extract dependency type bits.
*/
private static final int DEPENDENCIES_TYPE_MASK = NON_AREZ_DEPENDENCIES | AREZ_DEPENDENCIES_ONLY;
/**
* The observer can only read arez state.
*/
public static final int READ_ONLY = 1 << 25;
/**
* The observer can read or write arez state.
*/
public static final int READ_WRITE = 1 << 24;
/**
* Mask used to extract transaction mode bits.
*/
private static final int TRANSACTION_MASK = READ_ONLY | READ_WRITE;
/**
* The scheduler will be triggered when the observer is created to immediately invoke the
* {@link Observer#_observed} function. This configuration should not be specified if there
* is no {@link Observer#_observed} function supplied. This should not be
* specified if {@link #RUN_LATER} is specified.
*/
public static final int RUN_NOW = 1 << 23;
/**
* The scheduler will not be triggered when the observer is created. The observer either
* has no {@link Observer#_observed} function or is responsible for ensuring that
* {@link ArezContext#triggerScheduler()} is invoked at a later time. This should not be
* specified if {@link #RUN_NOW} is specified.
*/
public static final int RUN_LATER = 1 << 22;
/**
* Mask used to extract run type bits.
*/
private static final int RUN_TYPE_MASK = RUN_NOW | RUN_LATER;
/**
* The runtime will keep the observer reacting to dependencies until disposed. This is the default value for
* observers that supply a observed function but may be explicitly supplied when creating {@link ComputedValue}
* instances.
*/
public static final int KEEPALIVE = 1 << 21;
/**
* The flag is valid on observers associated with computed values and will deactivate the observer if the
* computed value has no observers.
*/
static final int DEACTIVATE_ON_UNOBSERVE = 1 << 20;
/**
* The flag is valid on observers where the observed function is invoked by the application.
*/
static final int SCHEDULED_EXTERNALLY = 1 << 19;
/**
* Mask used to extract react type bits.
*/
private static final int SCHEDULE_TYPE_MASK = KEEPALIVE | DEACTIVATE_ON_UNOBSERVE | SCHEDULED_EXTERNALLY;
/**
* Highest priority.
* This priority should be used when the observer will dispose or release other reactive elements
* (and thus remove elements from being scheduled).
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_HIGHEST = 0b001 << 16;
/**
* High priority.
* To reduce the chance that downstream elements will react multiple times within a single
* reaction round, this priority should be used when the observer may trigger many downstream
* reactions.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_HIGH = 0b010 << 16;
/**
* Normal priority if no other priority otherwise specified.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_NORMAL = 0b011 << 16;
/**
* Low priority.
* Usually used to schedule observers that reflect state onto non-reactive
* application components. i.e. Observers that are used to build html views,
* perform network operations etc. These reactions are often at low priority
* to avoid recalculation of dependencies (i.e. {@link ComputedValue}s) triggering
* this reaction multiple times within a single reaction round.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_LOW = 0b100 << 16;
/**
* Lowest priority. Use this priority if the observer is a {@link ComputedValue} that
* may be unobserved when a {@link #PRIORITY_LOW} observer reacts. This is used to avoid
* recomputing state that is likely to either be unobserved or recomputed as part of
* another observers reaction.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_LOWEST = 0b101 << 16;
/**
* Mask used to extract priority bits.
*/
private static final int PRIORITY_MASK = 0b111 << 16;
/**
* Shift used to extract priority after applying mask.
*/
private static final int PRIORITY_SHIFT = 16;
/**
* Mask that identifies the bits associated with static configuration.
*/
static final int CONFIG_FLAGS_MASK =
OBSERVE_LOWER_PRIORITY_DEPENDENCIES |
NESTED_ACTIONS_MASK |
DEPENDENCIES_TYPE_MASK |
TRANSACTION_MASK |
RUN_TYPE_MASK |
SCHEDULE_TYPE_MASK |
PRIORITY_MASK;
/**
* Flag indicating whether next scheduled invocation of {@link Observer} should invoke {@link Observer#_observed} or {@link Observer#_onDepsChanged}.
*/
static final int EXECUTE_OBSERVED_NEXT = 1 << 10;
/**
* The observer has been scheduled.
*/
static final int SCHEDULED = 1 << 9;
/**
* Mask used to extract state bits.
* State is the lowest bits as it is the most frequently accessed numeric fields
* and placing values at lower part of integer avoids a shift.
*/
private static final int STATE_MASK = 0b111;
/**
* The observer has been disposed.
*/
static final int STATE_DISPOSED = 0b001;
/**
* The observer is in the process of being disposed.
*/
static final int STATE_DISPOSING = 0b010;
/**
* The observer is not active and is not holding any data about it's dependencies.
* Typically mean this tracker observer has not been run or if it is a ComputedValue that
* there is no observer observing the associated ObservableValue.
*/
static final int STATE_INACTIVE = 0b011;
/**
* No change since last time observer was notified.
*/
static final int STATE_UP_TO_DATE = 0b100;
/**
* A transitive dependency has changed but it has not been determined if a shallow
* dependency has changed. The observer will need to check if shallow dependencies
* have changed. Only Derived observables will propagate POSSIBLY_STALE state.
*/
static final int STATE_POSSIBLY_STALE = 0b101;
/**
* A dependency has changed so the observer will need to recompute.
*/
static final int STATE_STALE = 0b110;
/**
* Mask that identifies the bits associated with runtime configuration.
*/
static final int RUNTIME_FLAGS_MASK = EXECUTE_OBSERVED_NEXT | SCHEDULED | STATE_MASK;
/**
* Return true if flags contains priority.
*
* @param flags the flags.
* @return true if flags contains priority.
*/
static boolean isPrioritySpecified( final int flags )
{
return 0 != ( flags & PRIORITY_MASK );
}
/**
* Return true if flags contains valid priority.
*
* @param flags the flags.
* @return true if flags contains priority.
*/
static boolean isPriorityValid( final int flags )
{
final int priorityIndex = getPriorityIndex( flags );
return priorityIndex <= 4 && priorityIndex >= 0;
}
/**
* Extract and return the priority value ranging from the highest priority 0 and lowest priority 4.
* This method assumes that flags has valid priority and will not attempt to re-check.
*
* @param flags the flags.
* @return the priority.
*/
static int getPriority( final int flags )
{
return flags & PRIORITY_MASK;
}
/**
* Extract and return the priority value ranging from the highest priority 0 and lowest priority 4.
* This method assumes that flags has valid priority and will not attempt to re-check.
*
* @param flags the flags.
* @return the priority.
*/
static int getPriorityIndex( final int flags )
{
return ( getPriority( flags ) >> PRIORITY_SHIFT ) - 1;
}
static int priority( final int flags )
{
return defaultFlagUnlessSpecified( flags, PRIORITY_MASK, PRIORITY_NORMAL );
}
static int nestedActionRule( final int flags )
{
return Arez.shouldCheckInvariants() ?
defaultFlagUnlessSpecified( flags, NESTED_ACTIONS_MASK, NESTED_ACTIONS_DISALLOWED ) :
0;
}
/**
* Return true if flags contains a valid nested action mode.
*
* @param flags the flags.
* @return true if flags contains valid nested action mode.
*/
static boolean isNestedActionsModeValid( final int flags )
{
return NESTED_ACTIONS_ALLOWED == ( flags & NESTED_ACTIONS_ALLOWED ) ^
NESTED_ACTIONS_DISALLOWED == ( flags & NESTED_ACTIONS_DISALLOWED );
}
/**
* Return true if flags contains transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
static boolean isTransactionModeSpecified( final int flags )
{
return 0 != ( flags & TRANSACTION_MASK );
}
static int transactionMode( final int flags )
{
return Arez.shouldEnforceTransactionType() ?
defaultFlagUnlessSpecified( flags, TRANSACTION_MASK, READ_ONLY ) :
0;
}
/**
* Return true if flags contains a valid transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
static boolean isTransactionModeValid( final int flags )
{
return 0 != ( flags & READ_ONLY ) ^ 0 != ( flags & READ_WRITE );
}
/**
* Return true if flags contains a valid react type.
*
* @param flags the flags.
* @return true if flags contains react type.
*/
static boolean isRunTypeValid( final int flags )
{
return RUN_NOW == ( flags & RUN_NOW ) ^ RUN_LATER == ( flags & RUN_LATER );
}
/**
* Return the default run type flag if run type not specified.
*
* @param flags the flags.
* @param defaultFlag the default flag to apply
* @return the default run type if run type unspecified else 0.
*/
static int runType( final int flags, final int defaultFlag )
{
return defaultFlagUnlessSpecified( flags, RUN_TYPE_MASK, defaultFlag );
}
/**
* Return name of transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
@Nonnull
static String getTransactionModeName( final int flags )
{
assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants();
if ( 0 != ( flags & READ_ONLY ) )
{
return "READ_ONLY";
}
else if ( 0 != ( flags & READ_WRITE ) )
{
return "READ_WRITE";
}
else
{
return "UNKNOWN(" + flags + ")";
}
}
/**
* Extract and return the schedule type.
*
* @param flags the flags.
* @return the schedule type.
*/
static int getScheduleType( final int flags )
{
return flags & SCHEDULE_TYPE_MASK;
}
/**
* Return true if flags contains a valid ScheduleType.
*
* @param flags the flags.
* @return true if flags contains a valid ScheduleType.
*/
static boolean isScheduleTypeValid( final int flags )
{
return KEEPALIVE == ( flags & KEEPALIVE ) ^
DEACTIVATE_ON_UNOBSERVE == ( flags & DEACTIVATE_ON_UNOBSERVE ) ^
SCHEDULED_EXTERNALLY == ( flags & SCHEDULED_EXTERNALLY );
}
/**
* Extract and return the observer's state.
*
* @param flags the flags.
* @return the state.
*/
static int getState( final int flags )
{
return flags & STATE_MASK;
}
/**
* Return the new value of flags when supplied with specified state.
*
* @param flags the flags.
* @param state the new state.
* @return the new flags.
*/
static int setState( final int flags, final int state )
{
return ( flags & ~STATE_MASK ) | state;
}
/**
* Return true if the state is UP_TO_DATE, POSSIBLY_STALE or STALE.
* The inverse of {@link #isNotActive(int)}
*
* @param flags the flags to check.
* @return true if the state is UP_TO_DATE, POSSIBLY_STALE or STALE.
*/
static boolean isActive( final int flags )
{
return getState( flags ) > STATE_INACTIVE;
}
/**
* Return true if the state is INACTIVE, DISPOSING or DISPOSED.
* The inverse of {@link #isActive(int)}
*
* @param flags the flags to check.
* @return true if the state is INACTIVE, DISPOSING or DISPOSED.
*/
static boolean isNotActive( final int flags )
{
return !isActive( flags );
}
/**
* Return the least stale observer state. if the state is not active
* then the {@link #STATE_UP_TO_DATE} will be returned.
*
* @param flags the flags to check.
* @return the least stale observer state.
*/
static int getLeastStaleObserverState( final int flags )
{
final int state = getState( flags );
return state > STATE_INACTIVE ? state : STATE_UP_TO_DATE;
}
/**
* Return the state as a string.
*
* @param state the state value. One of the STATE_* constants
* @return the string describing state.
*/
@Nonnull
static String getStateName( final int state )
{
assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants();
switch ( state )
{
case STATE_DISPOSED:
return "DISPOSED";
case STATE_DISPOSING:
return "DISPOSING";
case STATE_INACTIVE:
return "INACTIVE";
case STATE_POSSIBLY_STALE:
return "POSSIBLY_STALE";
case STATE_STALE:
return "STALE";
case STATE_UP_TO_DATE:
return "UP_TO_DATE";
default:
return "UNKNOWN(" + state + ")";
}
}
private Flags()
{
}
/**
* Return the default flag unless a value in mask is specified.
*
* @param flags the flags.
* @param mask the mask.
* @param defaultFlag the default flag to apply
* @return the default flag unless flag has value.
*/
private static int defaultFlagUnlessSpecified( final int flags, final int mask, final int defaultFlag )
{
return 0 != ( flags & mask ) ? 0 : defaultFlag;
}
}
| core/src/main/java/arez/Flags.java | package arez;
import javax.annotation.Nonnull;
/**
* Flags that can be passed when creating observers that determine the configuration of the observer.
* The class also contains constants and methods used to extract runtime state from Observers.
*/
public final class Flags
{
/**
* Flag indicating that the Observer is allowed to observe {@link ComputedValue} instances with a lower priority.
*/
public static final int OBSERVE_LOWER_PRIORITY_DEPENDENCIES = 1 << 30;
/**
* Indicates that the an action can be created from within the Observers observed function.
*/
public static final int NESTED_ACTIONS_ALLOWED = 1 << 29;
/**
* Indicates that the an action must not be created from within the Observers observed function.
*/
public static final int NESTED_ACTIONS_DISALLOWED = 1 << 28;
/**
* Mask to extract "NESTED_ACTIONS" option so can derive default value if required.
*/
private static final int NESTED_ACTIONS_MASK = NESTED_ACTIONS_ALLOWED | NESTED_ACTIONS_DISALLOWED;
/**
* Flag set if the application code can invoke {@link Observer#reportStale()} or {@link ComputedValue#reportPossiblyChanged()} to indicate non-arez dependency has changed.
*/
public static final int NON_AREZ_DEPENDENCIES = 1 << 27;
/**
* Flag set set if the application code can not invoke {@link Observer#reportStale()} or {@link ComputedValue#reportPossiblyChanged()} to indicate dependency has changed.
*/
public static final int AREZ_DEPENDENCIES_ONLY = 1 << 26;
/**
* Mask used to extract dependency type bits.
*/
private static final int DEPENDENCIES_TYPE_MASK = NON_AREZ_DEPENDENCIES | AREZ_DEPENDENCIES_ONLY;
/**
* The observer can only read arez state.
*/
public static final int READ_ONLY = 1 << 25;
/**
* The observer can read or write arez state.
*/
public static final int READ_WRITE = 1 << 24;
/**
* Mask used to extract transaction mode bits.
*/
private static final int TRANSACTION_MASK = READ_ONLY | READ_WRITE;
/**
* The scheduler will be triggered when the observer is created to immediately invoke the
* {@link Observer#_observed} function. This configuration should not be specified if there
* is no {@link Observer#_observed} function supplied. This should not be
* specified if {@link #RUN_LATER} is specified.
*/
public static final int RUN_NOW = 1 << 23;
/**
* The scheduler will not be triggered when the observer is created. The observer either
* has no {@link Observer#_observed} function or is responsible for ensuring that
* {@link ArezContext#triggerScheduler()} is invoked at a later time. This should not be
* specified if {@link #RUN_NOW} is specified.
*/
public static final int RUN_LATER = 1 << 22;
/**
* Mask used to extract run type bits.
*/
private static final int RUN_TYPE_MASK = RUN_NOW | RUN_LATER;
/**
* The runtime will keep the observer reacting to dependencies until disposed. This should not be
* specified if {@link #DEACTIVATE_ON_UNOBSERVE} is specified. This is the default value for observers
* that supply a observed function.
*/
public static final int KEEPALIVE = 1 << 21;
/**
* The flag is valid on observers associated with computed values and will deactivate the observer if the
* computed value has no observers. This should not be specified if {@link #KEEPALIVE} is specified.
*/
public static final int DEACTIVATE_ON_UNOBSERVE = 1 << 20;
/**
* The flag is valid on observers associated with computed values and will deactivate the observer if the
* computed value has no observers. This should not be specified if {@link #KEEPALIVE} is specified.
*/
public static final int SCHEDULED_EXTERNALLY = 1 << 19;
/**
* Mask used to extract react type bits.
*/
private static final int SCHEDULE_TYPE_MASK = KEEPALIVE | DEACTIVATE_ON_UNOBSERVE | SCHEDULED_EXTERNALLY;
/**
* Highest priority.
* This priority should be used when the observer will dispose or release other reactive elements
* (and thus remove elements from being scheduled).
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_HIGHEST = 0b001 << 16;
/**
* High priority.
* To reduce the chance that downstream elements will react multiple times within a single
* reaction round, this priority should be used when the observer may trigger many downstream
* reactions.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_HIGH = 0b010 << 16;
/**
* Normal priority if no other priority otherwise specified.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_NORMAL = 0b011 << 16;
/**
* Low priority.
* Usually used to schedule observers that reflect state onto non-reactive
* application components. i.e. Observers that are used to build html views,
* perform network operations etc. These reactions are often at low priority
* to avoid recalculation of dependencies (i.e. {@link ComputedValue}s) triggering
* this reaction multiple times within a single reaction round.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_LOW = 0b100 << 16;
/**
* Lowest priority. Use this priority if the observer is a {@link ComputedValue} that
* may be unobserved when a {@link #PRIORITY_LOW} observer reacts. This is used to avoid
* recomputing state that is likely to either be unobserved or recomputed as part of
* another observers reaction.
* <p>Only one of the PRIORITY_* flags should be applied to observer.</p>
*/
public static final int PRIORITY_LOWEST = 0b101 << 16;
/**
* Mask used to extract priority bits.
*/
private static final int PRIORITY_MASK = 0b111 << 16;
/**
* Shift used to extract priority after applying mask.
*/
private static final int PRIORITY_SHIFT = 16;
/**
* Mask that identifies the bits associated with static configuration.
*/
static final int CONFIG_FLAGS_MASK =
OBSERVE_LOWER_PRIORITY_DEPENDENCIES |
NESTED_ACTIONS_MASK |
DEPENDENCIES_TYPE_MASK |
TRANSACTION_MASK |
RUN_TYPE_MASK |
SCHEDULE_TYPE_MASK |
PRIORITY_MASK;
/**
* Flag indicating whether next scheduled invocation of {@link Observer} should invoke {@link Observer#_observed} or {@link Observer#_onDepsChanged}.
*/
static final int EXECUTE_OBSERVED_NEXT = 1 << 10;
/**
* The observer has been scheduled.
*/
static final int SCHEDULED = 1 << 9;
/**
* Mask used to extract state bits.
* State is the lowest bits as it is the most frequently accessed numeric fields
* and placing values at lower part of integer avoids a shift.
*/
private static final int STATE_MASK = 0b111;
/**
* The observer has been disposed.
*/
static final int STATE_DISPOSED = 0b001;
/**
* The observer is in the process of being disposed.
*/
static final int STATE_DISPOSING = 0b010;
/**
* The observer is not active and is not holding any data about it's dependencies.
* Typically mean this tracker observer has not been run or if it is a ComputedValue that
* there is no observer observing the associated ObservableValue.
*/
static final int STATE_INACTIVE = 0b011;
/**
* No change since last time observer was notified.
*/
static final int STATE_UP_TO_DATE = 0b100;
/**
* A transitive dependency has changed but it has not been determined if a shallow
* dependency has changed. The observer will need to check if shallow dependencies
* have changed. Only Derived observables will propagate POSSIBLY_STALE state.
*/
static final int STATE_POSSIBLY_STALE = 0b101;
/**
* A dependency has changed so the observer will need to recompute.
*/
static final int STATE_STALE = 0b110;
/**
* Mask that identifies the bits associated with runtime configuration.
*/
static final int RUNTIME_FLAGS_MASK = EXECUTE_OBSERVED_NEXT | SCHEDULED | STATE_MASK;
/**
* Return true if flags contains priority.
*
* @param flags the flags.
* @return true if flags contains priority.
*/
static boolean isPrioritySpecified( final int flags )
{
return 0 != ( flags & PRIORITY_MASK );
}
/**
* Return true if flags contains valid priority.
*
* @param flags the flags.
* @return true if flags contains priority.
*/
static boolean isPriorityValid( final int flags )
{
final int priorityIndex = getPriorityIndex( flags );
return priorityIndex <= 4 && priorityIndex >= 0;
}
/**
* Extract and return the priority value ranging from the highest priority 0 and lowest priority 4.
* This method assumes that flags has valid priority and will not attempt to re-check.
*
* @param flags the flags.
* @return the priority.
*/
static int getPriority( final int flags )
{
return flags & PRIORITY_MASK;
}
/**
* Extract and return the priority value ranging from the highest priority 0 and lowest priority 4.
* This method assumes that flags has valid priority and will not attempt to re-check.
*
* @param flags the flags.
* @return the priority.
*/
static int getPriorityIndex( final int flags )
{
return ( getPriority( flags ) >> PRIORITY_SHIFT ) - 1;
}
static int priority( final int flags )
{
return defaultFlagUnlessSpecified( flags, PRIORITY_MASK, PRIORITY_NORMAL );
}
static int nestedActionRule( final int flags )
{
return Arez.shouldCheckInvariants() ?
defaultFlagUnlessSpecified( flags, NESTED_ACTIONS_MASK, NESTED_ACTIONS_DISALLOWED ) :
0;
}
/**
* Return true if flags contains a valid nested action mode.
*
* @param flags the flags.
* @return true if flags contains valid nested action mode.
*/
static boolean isNestedActionsModeValid( final int flags )
{
return NESTED_ACTIONS_ALLOWED == ( flags & NESTED_ACTIONS_ALLOWED ) ^
NESTED_ACTIONS_DISALLOWED == ( flags & NESTED_ACTIONS_DISALLOWED );
}
/**
* Return true if flags contains transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
static boolean isTransactionModeSpecified( final int flags )
{
return 0 != ( flags & TRANSACTION_MASK );
}
static int transactionMode( final int flags )
{
return Arez.shouldEnforceTransactionType() ?
defaultFlagUnlessSpecified( flags, TRANSACTION_MASK, READ_ONLY ) :
0;
}
/**
* Return true if flags contains a valid transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
static boolean isTransactionModeValid( final int flags )
{
return 0 != ( flags & READ_ONLY ) ^ 0 != ( flags & READ_WRITE );
}
/**
* Return true if flags contains a valid react type.
*
* @param flags the flags.
* @return true if flags contains react type.
*/
static boolean isRunTypeValid( final int flags )
{
return RUN_NOW == ( flags & RUN_NOW ) ^ RUN_LATER == ( flags & RUN_LATER );
}
/**
* Return the default run type flag if run type not specified.
*
* @param flags the flags.
* @param defaultFlag the default flag to apply
* @return the default run type if run type unspecified else 0.
*/
static int runType( final int flags, final int defaultFlag )
{
return defaultFlagUnlessSpecified( flags, RUN_TYPE_MASK, defaultFlag );
}
/**
* Return name of transaction mode.
*
* @param flags the flags.
* @return true if flags contains transaction mode.
*/
@Nonnull
static String getTransactionModeName( final int flags )
{
assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants();
if ( 0 != ( flags & READ_ONLY ) )
{
return "READ_ONLY";
}
else if ( 0 != ( flags & READ_WRITE ) )
{
return "READ_WRITE";
}
else
{
return "UNKNOWN(" + flags + ")";
}
}
/**
* Extract and return the schedule type.
*
* @param flags the flags.
* @return the schedule type.
*/
static int getScheduleType( final int flags )
{
return flags & SCHEDULE_TYPE_MASK;
}
/**
* Return true if flags contains a valid ScheduleType.
*
* @param flags the flags.
* @return true if flags contains a valid ScheduleType.
*/
static boolean isScheduleTypeValid( final int flags )
{
return KEEPALIVE == ( flags & KEEPALIVE ) ^
DEACTIVATE_ON_UNOBSERVE == ( flags & DEACTIVATE_ON_UNOBSERVE ) ^
SCHEDULED_EXTERNALLY == ( flags & SCHEDULED_EXTERNALLY );
}
/**
* Extract and return the observer's state.
*
* @param flags the flags.
* @return the state.
*/
static int getState( final int flags )
{
return flags & STATE_MASK;
}
/**
* Return the new value of flags when supplied with specified state.
*
* @param flags the flags.
* @param state the new state.
* @return the new flags.
*/
static int setState( final int flags, final int state )
{
return ( flags & ~STATE_MASK ) | state;
}
/**
* Return true if the state is UP_TO_DATE, POSSIBLY_STALE or STALE.
* The inverse of {@link #isNotActive(int)}
*
* @param flags the flags to check.
* @return true if the state is UP_TO_DATE, POSSIBLY_STALE or STALE.
*/
static boolean isActive( final int flags )
{
return getState( flags ) > STATE_INACTIVE;
}
/**
* Return true if the state is INACTIVE, DISPOSING or DISPOSED.
* The inverse of {@link #isActive(int)}
*
* @param flags the flags to check.
* @return true if the state is INACTIVE, DISPOSING or DISPOSED.
*/
static boolean isNotActive( final int flags )
{
return !isActive( flags );
}
/**
* Return the least stale observer state. if the state is not active
* then the {@link #STATE_UP_TO_DATE} will be returned.
*
* @param flags the flags to check.
* @return the least stale observer state.
*/
static int getLeastStaleObserverState( final int flags )
{
final int state = getState( flags );
return state > STATE_INACTIVE ? state : STATE_UP_TO_DATE;
}
/**
* Return the state as a string.
*
* @param state the state value. One of the STATE_* constants
* @return the string describing state.
*/
@Nonnull
static String getStateName( final int state )
{
assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants();
switch ( state )
{
case STATE_DISPOSED:
return "DISPOSED";
case STATE_DISPOSING:
return "DISPOSING";
case STATE_INACTIVE:
return "INACTIVE";
case STATE_POSSIBLY_STALE:
return "POSSIBLY_STALE";
case STATE_STALE:
return "STALE";
case STATE_UP_TO_DATE:
return "UP_TO_DATE";
default:
return "UNKNOWN(" + state + ")";
}
}
private Flags()
{
}
/**
* Return the default flag unless a value in mask is specified.
*
* @param flags the flags.
* @param mask the mask.
* @param defaultFlag the default flag to apply
* @return the default flag unless flag has value.
*/
private static int defaultFlagUnlessSpecified( final int flags, final int mask, final int defaultFlag )
{
return 0 != ( flags & mask ) ? 0 : defaultFlag;
}
}
| Improve documentation for some flags and make a few flags package access
| core/src/main/java/arez/Flags.java | Improve documentation for some flags and make a few flags package access | <ide><path>ore/src/main/java/arez/Flags.java
<ide> */
<ide> private static final int RUN_TYPE_MASK = RUN_NOW | RUN_LATER;
<ide> /**
<del> * The runtime will keep the observer reacting to dependencies until disposed. This should not be
<del> * specified if {@link #DEACTIVATE_ON_UNOBSERVE} is specified. This is the default value for observers
<del> * that supply a observed function.
<add> * The runtime will keep the observer reacting to dependencies until disposed. This is the default value for
<add> * observers that supply a observed function but may be explicitly supplied when creating {@link ComputedValue}
<add> * instances.
<ide> */
<ide> public static final int KEEPALIVE = 1 << 21;
<ide> /**
<ide> * The flag is valid on observers associated with computed values and will deactivate the observer if the
<del> * computed value has no observers. This should not be specified if {@link #KEEPALIVE} is specified.
<del> */
<del> public static final int DEACTIVATE_ON_UNOBSERVE = 1 << 20;
<del> /**
<del> * The flag is valid on observers associated with computed values and will deactivate the observer if the
<del> * computed value has no observers. This should not be specified if {@link #KEEPALIVE} is specified.
<del> */
<del> public static final int SCHEDULED_EXTERNALLY = 1 << 19;
<add> * computed value has no observers.
<add> */
<add> static final int DEACTIVATE_ON_UNOBSERVE = 1 << 20;
<add> /**
<add> * The flag is valid on observers where the observed function is invoked by the application.
<add> */
<add> static final int SCHEDULED_EXTERNALLY = 1 << 19;
<ide> /**
<ide> * Mask used to extract react type bits.
<ide> */ |
|
Java | apache-2.0 | f435ce4d1984a5a60b3b03f50083484533326e2d | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2018 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.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.template.EverywhereContextType;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.TreeTraversal;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.PlatformColors;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class LiveTemplateSettingsEditor extends JPanel {
private final TemplateImpl myTemplate;
private final Runnable myNodeChanged;
private final JTextField myKeyField;
private final JTextField myDescription;
private final Editor myTemplateEditor;
private JComboBox myExpandByCombo;
private final String myDefaultShortcutItem;
private JCheckBox myCbReformat;
private JButton myEditVariablesButton;
private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");
private static final String NONE = CodeInsightBundle.message("template.shortcut.none");
private final Map<TemplateOptionalProcessor, Boolean> myOptions;
private final TemplateContext myContext;
private JBPopup myContextPopup;
private Dimension myLastSize;
private JPanel myTemplateOptionsPanel;
public LiveTemplateSettingsEditor(TemplateImpl template,
final String defaultShortcut,
Map<TemplateOptionalProcessor, Boolean> options,
TemplateContext context, final Runnable nodeChanged, boolean allowNoContext) {
super(new BorderLayout());
myOptions = options;
myContext = context;
myTemplate = template;
myNodeChanged = nodeChanged;
myDefaultShortcutItem = CodeInsightBundle.message("dialog.edit.template.shortcut.default", defaultShortcut);
myKeyField = new JTextField(20);
myDescription = new JTextField(100);
myTemplateEditor = TemplateEditorUtil.createEditor(false, myTemplate.getString(), context);
myTemplate.setId(null);
createComponents(allowNoContext);
myKeyField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(javax.swing.event.DocumentEvent e) {
myTemplate.setKey(StringUtil.notNullize(myKeyField.getText()).trim());
myNodeChanged.run();
}
});
myDescription.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(javax.swing.event.DocumentEvent e) {
myTemplate.setDescription(myDescription.getText());
myNodeChanged.run();
}
});
new UiNotifyConnector(this, new Activatable.Adapter() {
@Override
public void hideNotify() {
disposeContextPopup();
}
});
}
public TemplateImpl getTemplate() {
return myTemplate;
}
void dispose() {
TemplateEditorUtil.disposeTemplateEditor(myTemplateEditor);
}
private void createComponents(boolean allowNoContexts) {
JPanel panel = new JPanel(new GridBagLayout());
GridBag gb = new GridBag().setDefaultInsets(4, 4, 4, 4).setDefaultWeightY(1).setDefaultFill(GridBagConstraints.BOTH);
JPanel editorPanel = new JPanel(new BorderLayout(4, 4));
editorPanel.setPreferredSize(JBUI.size(250, 100));
editorPanel.setMinimumSize(editorPanel.getPreferredSize());
editorPanel.add(myTemplateEditor.getComponent(), BorderLayout.CENTER);
JLabel templateTextLabel = new JLabel(CodeInsightBundle.message("dialog.edit.template.template.text.title"));
templateTextLabel.setLabelFor(myTemplateEditor.getContentComponent());
editorPanel.add(templateTextLabel, BorderLayout.NORTH);
editorPanel.setFocusable(false);
panel.add(editorPanel, gb.nextLine().next().weighty(1).weightx(1).coverColumn(2));
myEditVariablesButton = new JButton(CodeInsightBundle.message("dialog.edit.template.button.edit.variables"));
myEditVariablesButton.setDefaultCapable(false);
myEditVariablesButton.setMaximumSize(myEditVariablesButton.getPreferredSize());
panel.add(myEditVariablesButton, gb.next().weighty(0));
myTemplateOptionsPanel = new JPanel(new BorderLayout());
myTemplateOptionsPanel.add(createTemplateOptionsPanel());
panel.add(myTemplateOptionsPanel, gb.nextLine().next().next().coverColumn(2).weighty(1));
panel.add(createShortContextPanel(allowNoContexts), gb.nextLine().next().weighty(0).fillCellNone().anchor(GridBagConstraints.WEST));
myTemplateEditor.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void documentChanged(DocumentEvent e) {
validateEditVariablesButton();
myTemplate.setString(myTemplateEditor.getDocument().getText());
applyVariables(updateVariablesByTemplateText());
myNodeChanged.run();
}
});
myEditVariablesButton.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(@NotNull ActionEvent e) {
editVariables();
}
}
);
add(createNorthPanel(), BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private void applyVariables(final List<Variable> variables) {
myTemplate.removeAllParsed();
for (Variable variable : variables) {
myTemplate.addVariable(variable.getName(), variable.getExpressionString(), variable.getDefaultValueString(),
variable.isAlwaysStopAt());
}
myTemplate.parseSegments();
}
@NotNull
private JComponent createNorthPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBag gb = new GridBag().setDefaultInsets(4, 4, 4, 4).setDefaultWeightY(1).setDefaultFill(GridBagConstraints.BOTH);
JLabel keyPrompt = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.abbreviation"));
keyPrompt.setLabelFor(myKeyField);
panel.add(keyPrompt, gb.nextLine().next());
panel.add(myKeyField, gb.next().weightx(1));
JLabel descriptionPrompt = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.description"));
descriptionPrompt.setLabelFor(myDescription);
panel.add(descriptionPrompt, gb.next());
panel.add(myDescription, gb.next().weightx(3));
return panel;
}
private JPanel createTemplateOptionsPanel() {
JPanel panel = new JPanel();
panel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("dialog.edit.template.options.title"),
true));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weighty = 0;
gbConstraints.weightx = 0;
gbConstraints.gridy = 0;
JLabel expandWithLabel = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.expand.with"));
panel.add(expandWithLabel, gbConstraints);
gbConstraints.gridx = 1;
gbConstraints.insets = JBUI.insetsLeft(4);
myExpandByCombo = new ComboBox<>(new String[]{myDefaultShortcutItem, SPACE, TAB, ENTER, NONE});
myExpandByCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(@NotNull ItemEvent e) {
Object selectedItem = myExpandByCombo.getSelectedItem();
if(myDefaultShortcutItem.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.DEFAULT_CHAR);
}
else if(TAB.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.TAB_CHAR);
}
else if(ENTER.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.ENTER_CHAR);
}
else if (SPACE.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.SPACE_CHAR);
}
else {
myTemplate.setShortcutChar(TemplateSettings.NONE_CHAR);
}
}
});
expandWithLabel.setLabelFor(myExpandByCombo);
panel.add(myExpandByCombo, gbConstraints);
gbConstraints.weightx = 1;
gbConstraints.gridx = 2;
panel.add(new JPanel(), gbConstraints);
gbConstraints.gridx = 0;
gbConstraints.gridy++;
gbConstraints.gridwidth = 3;
myCbReformat = new JCheckBox(CodeInsightBundle.message("dialog.edit.template.checkbox.reformat.according.to.style"));
panel.add(myCbReformat, gbConstraints);
for (final TemplateOptionalProcessor processor: myOptions.keySet()) {
if (!processor.isVisible(myTemplate, myContext)) continue;
gbConstraints.gridy++;
final JCheckBox cb = new JCheckBox(processor.getOptionName());
panel.add(cb, gbConstraints);
cb.setSelected(myOptions.get(processor).booleanValue());
cb.addActionListener(e -> myOptions.put(processor, cb.isSelected()));
}
gbConstraints.weighty = 1;
gbConstraints.gridy++;
panel.add(new JPanel(), gbConstraints);
return panel;
}
private List<TemplateContextType> getApplicableContexts() {
ArrayList<TemplateContextType> result = new ArrayList<>();
for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
if (myContext.isEnabled(type)) {
result.add(type);
}
}
return result;
}
private JPanel createShortContextPanel(final boolean allowNoContexts) {
JPanel panel = new JPanel(new BorderLayout());
final JLabel ctxLabel = new JLabel();
final JLabel change = new JLabel();
change.setForeground(PlatformColors.BLUE);
change.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(ctxLabel, BorderLayout.CENTER);
panel.add(change, BorderLayout.EAST);
final Runnable updateLabel = () -> {
myExpandByCombo.setEnabled(isExpandableFromEditor());
updateHighlighter();
StringBuilder sb = new StringBuilder();
String oldPrefix = "";
for (TemplateContextType type : getApplicableContexts()) {
final TemplateContextType base = type.getBaseContextType();
String ownName = presentableName(type);
String prefix = "";
if (base != null && !(base instanceof EverywhereContextType)) {
prefix = presentableName(base) + ": ";
ownName = StringUtil.decapitalize(ownName);
}
if (type instanceof EverywhereContextType) {
ownName = "Other";
}
if (sb.length() > 0) {
sb.append(oldPrefix.equals(prefix) ? ", " : "; ");
}
if (!oldPrefix.equals(prefix)) {
sb.append(prefix);
oldPrefix = prefix;
}
sb.append(ownName);
}
String contexts = "Applicable in " + sb.toString();
change.setText("Change");
final boolean noContexts = sb.length() == 0;
if (noContexts) {
if (!allowNoContexts) {
ctxLabel.setForeground(JBColor.RED);
}
contexts = "No applicable contexts" + (allowNoContexts ? "" : " yet");
ctxLabel.setIcon(AllIcons.General.BalloonWarning);
change.setText("Define");
}
else {
ctxLabel.setForeground(UIUtil.getLabelForeground());
ctxLabel.setIcon(null);
}
ctxLabel.setText(StringUtil.first(contexts + ". ", 100, true));
myTemplateOptionsPanel.removeAll();
myTemplateOptionsPanel.add(createTemplateOptionsPanel());
};
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent e, int clickCount) {
if (disposeContextPopup()) return false;
final JPanel content = createPopupContextPanel(updateLabel, myContext);
Dimension prefSize = content.getPreferredSize();
if (myLastSize != null && (myLastSize.width > prefSize.width || myLastSize.height > prefSize.height)) {
content.setPreferredSize(new Dimension(Math.max(prefSize.width, myLastSize.width), Math.max(prefSize.height, myLastSize.height)));
}
myContextPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(content, null).setResizable(true).createPopup();
myContextPopup.show(new RelativePoint(change, new Point(change.getWidth() , -content.getPreferredSize().height - 10)));
myContextPopup.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
myLastSize = content.getSize();
}
});
return true;
}
}.installOn(change);
updateLabel.run();
return panel;
}
@NotNull
private static String presentableName(TemplateContextType type) {
return UIUtil.removeMnemonic(type.getPresentableName());
}
private boolean disposeContextPopup() {
if (myContextPopup != null && myContextPopup.isVisible()) {
myContextPopup.cancel();
myContextPopup = null;
return true;
}
return false;
}
static JPanel createPopupContextPanel(final Runnable onChange, final TemplateContext context) {
JPanel panel = new JPanel(new BorderLayout());
MultiMap<TemplateContextType, TemplateContextType> hierarchy = MultiMap.createLinked();
for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
hierarchy.putValue(type.getBaseContextType(), type);
}
final CheckedTreeNode root = new CheckedTreeNode(Pair.create(null, "Hi"));
final CheckboxTree checkboxTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer() {
@Override
public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final Object o = ((DefaultMutableTreeNode)value).getUserObject();
if (o instanceof Pair) {
getTextRenderer().append((String)((Pair)o).second);
}
}
}, root) {
@Override
protected void onNodeStateChanged(CheckedTreeNode node) {
final TemplateContextType type = (TemplateContextType)((Pair)node.getUserObject()).first;
if (type != null) {
boolean enabled = node.isChecked();
context.setEnabled(type, enabled);
for (TemplateContextType inheritor : hierarchy.get(type)) {
if (context.getOwnValue(inheritor) == null) {
context.setEnabled(inheritor, !enabled);
}
}
}
onChange.run();
}
};
for (TemplateContextType type : sortContexts(hierarchy.get(null))) {
addContextNode(hierarchy, root, type, context);
}
((DefaultTreeModel)checkboxTree.getModel()).nodeStructureChanged(root);
TreeUtil.treeNodeTraverser(root).traverse(TreeTraversal.POST_ORDER_DFS).consumeEach(_node -> {
final CheckedTreeNode node = (CheckedTreeNode)_node;
if (node.isChecked()) {
final TreeNode[] path = node.getPath();
if (path != null) {
checkboxTree.expandPath(new TreePath(path).getParentPath());
}
}
});
TreeUtil.expand(checkboxTree, 2);
panel.add(ScrollPaneFactory.createScrollPane(checkboxTree));
final Dimension size = checkboxTree.getPreferredSize();
panel.setPreferredSize(new Dimension(size.width + 30, Math.min(size.height + 10, 500)));
return panel;
}
@NotNull
private static List<TemplateContextType> sortContexts(Collection<TemplateContextType> contextTypes) {
return ContainerUtil.sorted(contextTypes, (o1, o2) -> StringUtil.compare(presentableName(o1), presentableName(o2), true));
}
private static void addContextNode(MultiMap<TemplateContextType, TemplateContextType> hierarchy,
CheckedTreeNode parent,
TemplateContextType type, TemplateContext context) {
Collection<TemplateContextType> children = hierarchy.get(type);
String name = presentableName(type);
CheckedTreeNode node = new CheckedTreeNode(Pair.create(children.isEmpty() ? type : null, name));
parent.add(node);
if (!children.isEmpty()) {
for (TemplateContextType child : sortContexts(children)) {
addContextNode(hierarchy, node, child, context);
}
final CheckedTreeNode other = new CheckedTreeNode(Pair.create(type, "Other"));
other.setChecked(context.isEnabled(type));
node.add(other);
}
node.setChecked(context.isEnabled(type));
}
private boolean isExpandableFromEditor() {
boolean hasNonExpandable = false;
for (TemplateContextType type : getApplicableContexts()) {
if (type.isExpandableFromEditor()) {
return true;
}
hasNonExpandable = true;
}
return !hasNonExpandable;
}
private void updateHighlighter() {
TemplateEditorUtil.setHighlighter(myTemplateEditor, ContainerUtil.getFirstItem(getApplicableContexts()));
}
private void validateEditVariablesButton() {
boolean hasVariables = !parseVariables().isEmpty();
myEditVariablesButton.setEnabled(hasVariables);
myEditVariablesButton.setToolTipText(hasVariables ? null : "Disabled because the template has no variables (surrounded with $ signs)");
}
void resetUi() {
myKeyField.setText(myTemplate.getKey());
myDescription.setText(myTemplate.getDescription());
if(myTemplate.getShortcutChar() == TemplateSettings.DEFAULT_CHAR) {
myExpandByCombo.setSelectedItem(myDefaultShortcutItem);
}
else if(myTemplate.getShortcutChar() == TemplateSettings.TAB_CHAR) {
myExpandByCombo.setSelectedItem(TAB);
}
else if(myTemplate.getShortcutChar() == TemplateSettings.ENTER_CHAR) {
myExpandByCombo.setSelectedItem(ENTER);
}
else if (myTemplate.getShortcutChar() == TemplateSettings.SPACE_CHAR) {
myExpandByCombo.setSelectedItem(SPACE);
}
else {
myExpandByCombo.setSelectedItem(TemplateSettings.NONE_CHAR);
}
CommandProcessor.getInstance().executeCommand(
null, () -> ApplicationManager.getApplication().runWriteAction(() -> {
final Document document = myTemplateEditor.getDocument();
document.replaceString(0, document.getTextLength(), myTemplate.getString());
}),
"",
null
);
myCbReformat.setSelected(myTemplate.isToReformat());
myCbReformat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@NotNull ActionEvent e) {
myTemplate.setToReformat(myCbReformat.isSelected());
}
});
myExpandByCombo.setEnabled(isExpandableFromEditor());
updateHighlighter();
validateEditVariablesButton();
}
private void editVariables() {
ArrayList<Variable> newVariables = updateVariablesByTemplateText();
EditVariableDialog editVariableDialog =
new EditVariableDialog(myTemplateEditor, myEditVariablesButton, newVariables, getApplicableContexts());
if (editVariableDialog.showAndGet()) {
applyVariables(newVariables);
}
}
private ArrayList<Variable> updateVariablesByTemplateText() {
List<Variable> oldVariables = getCurrentVariables();
Set<String> oldVariableNames = ContainerUtil.map2Set(oldVariables, variable -> variable.getName());
Map<String,Variable> newVariableNames = parseVariables();
int oldVariableNumber = 0;
for (Map.Entry<String, Variable> entry : newVariableNames.entrySet()) {
if(oldVariableNames.contains(entry.getKey())) {
Variable oldVariable = null;
for(;oldVariableNumber<oldVariables.size(); oldVariableNumber++) {
oldVariable = oldVariables.get(oldVariableNumber);
if(newVariableNames.get(oldVariable.getName()) != null) {
break;
}
oldVariable = null;
}
oldVariableNumber++;
if(oldVariable != null) {
entry.setValue(oldVariable);
}
}
}
return new ArrayList<>(newVariableNames.values());
}
private List<Variable> getCurrentVariables() {
List<Variable> myVariables = new ArrayList<>();
for(int i = 0; i < myTemplate.getVariableCount(); i++) {
myVariables.add(new Variable(myTemplate.getVariableNameAt(i),
myTemplate.getExpressionStringAt(i),
myTemplate.getDefaultValueStringAt(i),
myTemplate.isAlwaysStopAt(i)));
}
return myVariables;
}
public JTextField getKeyField() {
return myKeyField;
}
public void focusKey() {
myKeyField.selectAll();
//todo[peter,kirillk] without these invokeLaters this requestFocus conflicts with com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.MyDialog.MyWindowListener.windowOpened()
IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true);
final ModalityState modalityState = ModalityState.stateForComponent(myKeyField);
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true), modalityState), modalityState), modalityState);
}
private Map<String, Variable> parseVariables() {
Map<String,Variable> map = TemplateImplUtil.parseVariables(myTemplateEditor.getDocument().getCharsSequence());
map.keySet().removeAll(TemplateImpl.INTERNAL_VARS_SET);
return map;
}
}
| platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java | // Copyright 2000-2018 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.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.template.EverywhereContextType;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.TreeTraversal;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.PlatformColors;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class LiveTemplateSettingsEditor extends JPanel {
private final TemplateImpl myTemplate;
private final Runnable myNodeChanged;
private final JTextField myKeyField;
private final JTextField myDescription;
private final Editor myTemplateEditor;
private JComboBox myExpandByCombo;
private final String myDefaultShortcutItem;
private JCheckBox myCbReformat;
private JButton myEditVariablesButton;
private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");
private static final String NONE = CodeInsightBundle.message("template.shortcut.none");
private final Map<TemplateOptionalProcessor, Boolean> myOptions;
private final TemplateContext myContext;
private JBPopup myContextPopup;
private Dimension myLastSize;
private JPanel myTemplateOptionsPanel;
public LiveTemplateSettingsEditor(TemplateImpl template,
final String defaultShortcut,
Map<TemplateOptionalProcessor, Boolean> options,
TemplateContext context, final Runnable nodeChanged, boolean allowNoContext) {
super(new BorderLayout());
myOptions = options;
myContext = context;
myTemplate = template;
myNodeChanged = nodeChanged;
myDefaultShortcutItem = CodeInsightBundle.message("dialog.edit.template.shortcut.default", defaultShortcut);
myKeyField = new JTextField(20);
myDescription = new JTextField(100);
myTemplateEditor = TemplateEditorUtil.createEditor(false, myTemplate.getString(), context);
myTemplate.setId(null);
createComponents(allowNoContext);
myKeyField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(javax.swing.event.DocumentEvent e) {
myTemplate.setKey(StringUtil.notNullize(myKeyField.getText()).trim());
myNodeChanged.run();
}
});
myDescription.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(javax.swing.event.DocumentEvent e) {
myTemplate.setDescription(myDescription.getText());
myNodeChanged.run();
}
});
new UiNotifyConnector(this, new Activatable.Adapter() {
@Override
public void hideNotify() {
disposeContextPopup();
}
});
}
public TemplateImpl getTemplate() {
return myTemplate;
}
void dispose() {
TemplateEditorUtil.disposeTemplateEditor(myTemplateEditor);
}
private void createComponents(boolean allowNoContexts) {
JPanel panel = new JPanel(new GridBagLayout());
GridBag gb = new GridBag().setDefaultInsets(4, 4, 4, 4).setDefaultWeightY(1).setDefaultFill(GridBagConstraints.BOTH);
JPanel editorPanel = new JPanel(new BorderLayout(4, 4));
editorPanel.setPreferredSize(JBUI.size(250, 100));
editorPanel.setMinimumSize(editorPanel.getPreferredSize());
editorPanel.add(myTemplateEditor.getComponent(), BorderLayout.CENTER);
JLabel templateTextLabel = new JLabel(CodeInsightBundle.message("dialog.edit.template.template.text.title"));
templateTextLabel.setLabelFor(myTemplateEditor.getContentComponent());
editorPanel.add(templateTextLabel, BorderLayout.NORTH);
editorPanel.setFocusable(false);
panel.add(editorPanel, gb.nextLine().next().weighty(1).weightx(1).coverColumn(2));
myEditVariablesButton = new JButton(CodeInsightBundle.message("dialog.edit.template.button.edit.variables"));
myEditVariablesButton.setDefaultCapable(false);
myEditVariablesButton.setMaximumSize(myEditVariablesButton.getPreferredSize());
panel.add(myEditVariablesButton, gb.next().weighty(0));
myTemplateOptionsPanel = new JPanel(new BorderLayout());
myTemplateOptionsPanel.add(createTemplateOptionsPanel());
panel.add(myTemplateOptionsPanel, gb.nextLine().next().next().coverColumn(2).weighty(1));
panel.add(createShortContextPanel(allowNoContexts), gb.nextLine().next().weighty(0).fillCellNone().anchor(GridBagConstraints.WEST));
myTemplateEditor.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void documentChanged(DocumentEvent e) {
validateEditVariablesButton();
myTemplate.setString(myTemplateEditor.getDocument().getText());
applyVariables(updateVariablesByTemplateText());
myNodeChanged.run();
}
});
myEditVariablesButton.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(@NotNull ActionEvent e) {
editVariables();
}
}
);
add(createNorthPanel(), BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private void applyVariables(final List<Variable> variables) {
myTemplate.removeAllParsed();
for (Variable variable : variables) {
myTemplate.addVariable(variable.getName(), variable.getExpressionString(), variable.getDefaultValueString(),
variable.isAlwaysStopAt());
}
myTemplate.parseSegments();
}
@NotNull
private JComponent createNorthPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBag gb = new GridBag().setDefaultInsets(4, 4, 4, 4).setDefaultWeightY(1).setDefaultFill(GridBagConstraints.BOTH);
JLabel keyPrompt = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.abbreviation"));
keyPrompt.setLabelFor(myKeyField);
panel.add(keyPrompt, gb.nextLine().next());
panel.add(myKeyField, gb.next().weightx(1));
JLabel descriptionPrompt = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.description"));
descriptionPrompt.setLabelFor(myDescription);
panel.add(descriptionPrompt, gb.next());
panel.add(myDescription, gb.next().weightx(3));
return panel;
}
private JPanel createTemplateOptionsPanel() {
JPanel panel = new JPanel();
panel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("dialog.edit.template.options.title"),
true));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weighty = 0;
gbConstraints.weightx = 0;
gbConstraints.gridy = 0;
JLabel expandWithLabel = new JLabel(CodeInsightBundle.message("dialog.edit.template.label.expand.with"));
panel.add(expandWithLabel, gbConstraints);
gbConstraints.gridx = 1;
gbConstraints.insets = JBUI.insetsLeft(4);
myExpandByCombo = new ComboBox<>(new String[]{myDefaultShortcutItem, SPACE, TAB, ENTER, NONE});
myExpandByCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(@NotNull ItemEvent e) {
Object selectedItem = myExpandByCombo.getSelectedItem();
if(myDefaultShortcutItem.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.DEFAULT_CHAR);
}
else if(TAB.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.TAB_CHAR);
}
else if(ENTER.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.ENTER_CHAR);
}
else if (SPACE.equals(selectedItem)) {
myTemplate.setShortcutChar(TemplateSettings.SPACE_CHAR);
}
else {
myTemplate.setShortcutChar(TemplateSettings.NONE_CHAR);
}
}
});
expandWithLabel.setLabelFor(myExpandByCombo);
panel.add(myExpandByCombo, gbConstraints);
gbConstraints.weightx = 1;
gbConstraints.gridx = 2;
panel.add(new JPanel(), gbConstraints);
gbConstraints.gridx = 0;
gbConstraints.gridy++;
gbConstraints.gridwidth = 3;
myCbReformat = new JCheckBox(CodeInsightBundle.message("dialog.edit.template.checkbox.reformat.according.to.style"));
panel.add(myCbReformat, gbConstraints);
for (final TemplateOptionalProcessor processor: myOptions.keySet()) {
if (!processor.isVisible(myTemplate, myContext)) continue;
gbConstraints.gridy++;
final JCheckBox cb = new JCheckBox(processor.getOptionName());
panel.add(cb, gbConstraints);
cb.setSelected(myOptions.get(processor).booleanValue());
cb.addActionListener(e -> myOptions.put(processor, cb.isSelected()));
}
gbConstraints.weighty = 1;
gbConstraints.gridy++;
panel.add(new JPanel(), gbConstraints);
return panel;
}
private List<TemplateContextType> getApplicableContexts() {
ArrayList<TemplateContextType> result = new ArrayList<>();
for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
if (myContext.isEnabled(type)) {
result.add(type);
}
}
return result;
}
private JPanel createShortContextPanel(final boolean allowNoContexts) {
JPanel panel = new JPanel(new BorderLayout());
final JLabel ctxLabel = new JLabel();
final JLabel change = new JLabel();
change.setForeground(PlatformColors.BLUE);
change.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(ctxLabel, BorderLayout.CENTER);
panel.add(change, BorderLayout.EAST);
final Runnable updateLabel = () -> {
myExpandByCombo.setEnabled(isExpandableFromEditor());
updateHighlighter();
StringBuilder sb = new StringBuilder();
String oldPrefix = "";
for (TemplateContextType type : getApplicableContexts()) {
final TemplateContextType base = type.getBaseContextType();
String ownName = presentableName(type);
String prefix = "";
if (base != null && !(base instanceof EverywhereContextType)) {
prefix = presentableName(base) + ": ";
ownName = StringUtil.decapitalize(ownName);
}
if (type instanceof EverywhereContextType) {
ownName = "Other";
}
if (sb.length() > 0) {
sb.append(oldPrefix.equals(prefix) ? ", " : "; ");
}
if (!oldPrefix.equals(prefix)) {
sb.append(prefix);
oldPrefix = prefix;
}
sb.append(ownName);
}
String contexts = "Applicable in " + sb.toString();
change.setText("Change");
final boolean noContexts = sb.length() == 0;
if (noContexts) {
if (!allowNoContexts) {
ctxLabel.setForeground(JBColor.RED);
}
contexts = "No applicable contexts" + (allowNoContexts ? "" : " yet");
ctxLabel.setIcon(AllIcons.General.BalloonWarning);
change.setText("Define");
}
else {
ctxLabel.setForeground(UIUtil.getLabelForeground());
ctxLabel.setIcon(null);
}
ctxLabel.setText(StringUtil.first(contexts + ". ", 100, true));
myTemplateOptionsPanel.removeAll();
myTemplateOptionsPanel.add(createTemplateOptionsPanel());
};
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent e, int clickCount) {
if (disposeContextPopup()) return false;
final JPanel content = createPopupContextPanel(updateLabel, myContext);
Dimension prefSize = content.getPreferredSize();
if (myLastSize != null && (myLastSize.width > prefSize.width || myLastSize.height > prefSize.height)) {
content.setPreferredSize(new Dimension(Math.max(prefSize.width, myLastSize.width), Math.max(prefSize.height, myLastSize.height)));
}
myContextPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(content, null).setResizable(true).createPopup();
myContextPopup.show(new RelativePoint(change, new Point(change.getWidth() , -content.getPreferredSize().height - 10)));
myContextPopup.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
myLastSize = content.getSize();
}
});
return true;
}
}.installOn(change);
updateLabel.run();
return panel;
}
@NotNull
private static String presentableName(TemplateContextType type) {
return UIUtil.removeMnemonic(type.getPresentableName());
}
private boolean disposeContextPopup() {
if (myContextPopup != null && myContextPopup.isVisible()) {
myContextPopup.cancel();
myContextPopup = null;
return true;
}
return false;
}
static JPanel createPopupContextPanel(final Runnable onChange, final TemplateContext context) {
JPanel panel = new JPanel(new BorderLayout());
MultiMap<TemplateContextType, TemplateContextType> hierarchy = MultiMap.createLinked();
for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
hierarchy.putValue(type.getBaseContextType(), type);
}
final CheckedTreeNode root = new CheckedTreeNode(Pair.create(null, "Hi"));
final CheckboxTree checkboxTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer() {
@Override
public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final Object o = ((DefaultMutableTreeNode)value).getUserObject();
if (o instanceof Pair) {
getTextRenderer().append((String)((Pair)o).second);
}
}
}, root) {
@Override
protected void onNodeStateChanged(CheckedTreeNode node) {
final TemplateContextType type = (TemplateContextType)((Pair)node.getUserObject()).first;
if (type != null) {
context.setEnabled(type, node.isChecked());
if (node.isChecked()) {
for (TemplateContextType inheritor : hierarchy.get(type)) {
if (context.getOwnValue(inheritor) == null) {
context.setEnabled(inheritor, false);
}
}
}
}
onChange.run();
}
};
for (TemplateContextType type : sortContexts(hierarchy.get(null))) {
addContextNode(hierarchy, root, type, context);
}
((DefaultTreeModel)checkboxTree.getModel()).nodeStructureChanged(root);
TreeUtil.treeNodeTraverser(root).traverse(TreeTraversal.POST_ORDER_DFS).consumeEach(_node -> {
final CheckedTreeNode node = (CheckedTreeNode)_node;
if (node.isChecked()) {
final TreeNode[] path = node.getPath();
if (path != null) {
checkboxTree.expandPath(new TreePath(path).getParentPath());
}
}
});
TreeUtil.expand(checkboxTree, 2);
panel.add(ScrollPaneFactory.createScrollPane(checkboxTree));
final Dimension size = checkboxTree.getPreferredSize();
panel.setPreferredSize(new Dimension(size.width + 30, Math.min(size.height + 10, 500)));
return panel;
}
@NotNull
private static List<TemplateContextType> sortContexts(Collection<TemplateContextType> contextTypes) {
return ContainerUtil.sorted(contextTypes, (o1, o2) -> StringUtil.compare(presentableName(o1), presentableName(o2), true));
}
private static void addContextNode(MultiMap<TemplateContextType, TemplateContextType> hierarchy,
CheckedTreeNode parent,
TemplateContextType type, TemplateContext context) {
Collection<TemplateContextType> children = hierarchy.get(type);
String name = presentableName(type);
CheckedTreeNode node = new CheckedTreeNode(Pair.create(children.isEmpty() ? type : null, name));
parent.add(node);
if (!children.isEmpty()) {
for (TemplateContextType child : sortContexts(children)) {
addContextNode(hierarchy, node, child, context);
}
final CheckedTreeNode other = new CheckedTreeNode(Pair.create(type, "Other"));
other.setChecked(context.isEnabled(type));
node.add(other);
}
node.setChecked(context.isEnabled(type));
}
private boolean isExpandableFromEditor() {
boolean hasNonExpandable = false;
for (TemplateContextType type : getApplicableContexts()) {
if (type.isExpandableFromEditor()) {
return true;
}
hasNonExpandable = true;
}
return !hasNonExpandable;
}
private void updateHighlighter() {
TemplateEditorUtil.setHighlighter(myTemplateEditor, ContainerUtil.getFirstItem(getApplicableContexts()));
}
private void validateEditVariablesButton() {
boolean hasVariables = !parseVariables().isEmpty();
myEditVariablesButton.setEnabled(hasVariables);
myEditVariablesButton.setToolTipText(hasVariables ? null : "Disabled because the template has no variables (surrounded with $ signs)");
}
void resetUi() {
myKeyField.setText(myTemplate.getKey());
myDescription.setText(myTemplate.getDescription());
if(myTemplate.getShortcutChar() == TemplateSettings.DEFAULT_CHAR) {
myExpandByCombo.setSelectedItem(myDefaultShortcutItem);
}
else if(myTemplate.getShortcutChar() == TemplateSettings.TAB_CHAR) {
myExpandByCombo.setSelectedItem(TAB);
}
else if(myTemplate.getShortcutChar() == TemplateSettings.ENTER_CHAR) {
myExpandByCombo.setSelectedItem(ENTER);
}
else if (myTemplate.getShortcutChar() == TemplateSettings.SPACE_CHAR) {
myExpandByCombo.setSelectedItem(SPACE);
}
else {
myExpandByCombo.setSelectedItem(TemplateSettings.NONE_CHAR);
}
CommandProcessor.getInstance().executeCommand(
null, () -> ApplicationManager.getApplication().runWriteAction(() -> {
final Document document = myTemplateEditor.getDocument();
document.replaceString(0, document.getTextLength(), myTemplate.getString());
}),
"",
null
);
myCbReformat.setSelected(myTemplate.isToReformat());
myCbReformat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@NotNull ActionEvent e) {
myTemplate.setToReformat(myCbReformat.isSelected());
}
});
myExpandByCombo.setEnabled(isExpandableFromEditor());
updateHighlighter();
validateEditVariablesButton();
}
private void editVariables() {
ArrayList<Variable> newVariables = updateVariablesByTemplateText();
EditVariableDialog editVariableDialog =
new EditVariableDialog(myTemplateEditor, myEditVariablesButton, newVariables, getApplicableContexts());
if (editVariableDialog.showAndGet()) {
applyVariables(newVariables);
}
}
private ArrayList<Variable> updateVariablesByTemplateText() {
List<Variable> oldVariables = getCurrentVariables();
Set<String> oldVariableNames = ContainerUtil.map2Set(oldVariables, variable -> variable.getName());
Map<String,Variable> newVariableNames = parseVariables();
int oldVariableNumber = 0;
for (Map.Entry<String, Variable> entry : newVariableNames.entrySet()) {
if(oldVariableNames.contains(entry.getKey())) {
Variable oldVariable = null;
for(;oldVariableNumber<oldVariables.size(); oldVariableNumber++) {
oldVariable = oldVariables.get(oldVariableNumber);
if(newVariableNames.get(oldVariable.getName()) != null) {
break;
}
oldVariable = null;
}
oldVariableNumber++;
if(oldVariable != null) {
entry.setValue(oldVariable);
}
}
}
return new ArrayList<>(newVariableNames.values());
}
private List<Variable> getCurrentVariables() {
List<Variable> myVariables = new ArrayList<>();
for(int i = 0; i < myTemplate.getVariableCount(); i++) {
myVariables.add(new Variable(myTemplate.getVariableNameAt(i),
myTemplate.getExpressionStringAt(i),
myTemplate.getDefaultValueStringAt(i),
myTemplate.isAlwaysStopAt(i)));
}
return myVariables;
}
public JTextField getKeyField() {
return myKeyField;
}
public void focusKey() {
myKeyField.selectAll();
//todo[peter,kirillk] without these invokeLaters this requestFocus conflicts with com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.MyDialog.MyWindowListener.windowOpened()
IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true);
final ModalityState modalityState = ModalityState.stateForComponent(myKeyField);
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true), modalityState), modalityState), modalityState);
}
private Map<String, Variable> parseVariables() {
Map<String,Variable> map = TemplateImplUtil.parseVariables(myTemplateEditor.getDocument().getCharsSequence());
map.keySet().removeAll(TemplateImpl.INTERNAL_VARS_SET);
return map;
}
}
| IDEA-194876 When removing "Other" from "B" live template context, it's reset to "None"
| platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java | IDEA-194876 When removing "Other" from "B" live template context, it's reset to "None" | <ide><path>latform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java
<ide> protected void onNodeStateChanged(CheckedTreeNode node) {
<ide> final TemplateContextType type = (TemplateContextType)((Pair)node.getUserObject()).first;
<ide> if (type != null) {
<del> context.setEnabled(type, node.isChecked());
<del> if (node.isChecked()) {
<del> for (TemplateContextType inheritor : hierarchy.get(type)) {
<del> if (context.getOwnValue(inheritor) == null) {
<del> context.setEnabled(inheritor, false);
<del> }
<add> boolean enabled = node.isChecked();
<add> context.setEnabled(type, enabled);
<add> for (TemplateContextType inheritor : hierarchy.get(type)) {
<add> if (context.getOwnValue(inheritor) == null) {
<add> context.setEnabled(inheritor, !enabled);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | d14c2b678eee103da2161998fdac53b795eb0c09 | 0 | hawkular/hawkular-metrics,hawkular/hawkular-metrics,burmanm/hawkular-metrics,burmanm/hawkular-metrics,burmanm/hawkular-metrics,hawkular/hawkular-metrics,burmanm/hawkular-metrics,hawkular/hawkular-metrics | /*
* Copyright 2014-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.core.service;
import static java.time.ZoneOffset.UTC;
import static java.util.stream.Collectors.toMap;
import static org.hawkular.metrics.core.service.TimeUUIDUtils.getTimeUUID;
import static org.hawkular.metrics.model.MetricType.STRING;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.hawkular.metrics.core.service.compress.CompressedPointContainer;
import org.hawkular.metrics.core.service.log.CoreLogger;
import org.hawkular.metrics.core.service.log.CoreLogging;
import org.hawkular.metrics.core.service.transformers.BatchStatementTransformer;
import org.hawkular.metrics.core.service.transformers.BoundBatchStatementTransformer;
import org.hawkular.metrics.datetime.DateTimeService;
import org.hawkular.metrics.model.AvailabilityType;
import org.hawkular.metrics.model.DataPoint;
import org.hawkular.metrics.model.Metric;
import org.hawkular.metrics.model.MetricId;
import org.hawkular.metrics.model.MetricType;
import org.hawkular.metrics.model.Tenant;
import org.hawkular.rx.cassandra.driver.RxSession;
import org.hawkular.rx.cassandra.driver.RxSessionImpl;
import com.datastax.driver.core.AbstractTableMetadata;
import com.datastax.driver.core.AggregateMetadata;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.CodecRegistry;
import com.datastax.driver.core.FunctionMetadata;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.MaterializedViewMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.SchemaChangeListener;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SimpleStatement;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.Token;
import com.datastax.driver.core.TokenRange;
import com.datastax.driver.core.UserType;
import com.datastax.driver.core.exceptions.DriverException;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import rx.Observable;
import rx.exceptions.Exceptions;
import rx.schedulers.Schedulers;
/**
*
* @author John Sanda
*/
public class DataAccessImpl implements DataAccess {
private static final CoreLogger log = CoreLogging.getCoreLogger(DataAccessImpl.class);
public static final String OUT_OF_ORDER_TABLE_NAME = "data_0";
public static final String TEMP_TABLE_NAME_PROTOTYPE = "data_temp_";
public static final String TEMP_TABLE_NAME_FORMAT_STRING = TEMP_TABLE_NAME_PROTOTYPE + "%s";
public static final long DPART = 0;
private Session session;
private RxSession rxSession;
private LoadBalancingPolicy loadBalancingPolicy;
// Turn to MetricType agnostic
// See getMapKey(byte, int)
private NavigableMap<Long, Map<Integer, PreparedStatement>> prepMap;
// TODO Move all of these to a new class (Cassandra specific temp table) to allow multiple implementations (such
// as in-memory + WAL in Cassandra)
private TemporaryTableStatementCreator tableCreator = null;
private enum StatementType {
READ, WRITE, SCAN, CREATE, DELETE
}
private enum TempStatement {
// Should I map these to something else..? More like a key to the actual statement
dateRangeExclusive(byDateRangeExclusiveBase, StatementType.READ),
dateRangeExclusiveWithLimit(dateRangeExclusiveWithLimitBase, StatementType.READ),
dataByDateRangeExclusiveASC(dataByDateRangeExclusiveASCBase, StatementType.READ),
dataByDateRangeExclusiveWithLimitASC(dataByDateRangeExclusiveWithLimitASCBase, StatementType.READ),
SCAN_WITH_TOKEN_RANGES(scanTableBase, StatementType.SCAN),
CHECK_EXISTENCE_OF_METRIC_IN_TABLE(findMetricInDataBase, StatementType.SCAN),
LIST_ALL_METRICS_FROM_TABLE(findAllMetricsInDataBases, StatementType.SCAN),
INSERT_DATA(data, StatementType.WRITE),
INSERT_DATA_WITH_TAGS(dataWithTags, StatementType.WRITE),
CREATE_TABLE(TEMP_TABLE_BASE_CREATE, StatementType.CREATE),
// CREATE_WAL(TEMP_TABLE_WAL_CREATE, StatementType.CREATE);
DELETE_DATA(DELETE_FROM_DATA_BASE, StatementType.DELETE);
private final String statement;
private StatementType type;
TempStatement(String st, StatementType t) {
statement = st;
type = t;
}
public String getStatement() {
return statement;
}
public StatementType getType() {
return type;
}
}
// Read statement prototypes
private static String byDateRangeExclusiveBase =
"SELECT time, %s, tags FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ? AND time < ?";
private static String dateRangeExclusiveWithLimitBase =
"SELECT time, %s, tags FROM %s " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ? AND time < ?" +
" LIMIT ?";
private static String dataByDateRangeExclusiveASCBase =
"SELECT time, %s, tags FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC";
private static String dataByDateRangeExclusiveWithLimitASCBase =
"SELECT time, %s, tags FROM %s" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?";
private static String scanTableBase =
"SELECT tenant_id, type, metric, time, n_value, availability, l_value, tags, token(tenant_id, type, " +
"metric) FROM %s " +
"WHERE token(tenant_id, type, metric) > ? AND token(tenant_id, type, metric) <=" +
" ?";
// Create statement prototype
private static String TEMP_TABLE_BASE_CREATE = "CREATE TABLE %s ( " +
"tenant_id text, " +
"type tinyint, " +
"metric text, " +
"time timestamp, " +
"n_value double, " +
"availability blob, " +
"l_value bigint, " +
"tags map<text,text>, " +
"PRIMARY KEY ((tenant_id, type, metric), time)" +
") WITH CLUSTERING ORDER BY (time DESC)";
// For in-memory buffering
/*
private static String TEMP_TABLE_WAL_CREATE = "CREATE TABLE %s (" +
"tenant_id text, " +
"type tinyint, " +
"metric text, " +
"dpart bigint, " +
"time timestamp, " +
"count int, " +
"value blob, " +
"tags blob, " +
"PRIMARY KEY ((tenant_id, type, metric), time) " +
") WITH CLUSTERING ORDER BY (time DESC)";
*/
// Insert statement prototypes
private static String data = "UPDATE %s " +
"SET %s = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time = ? ";
private static String dataWithTags = "UPDATE %s " +
"SET %s = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time = ? ";
// Metric definition prototypes
private static String findMetricInDataBase = "SELECT DISTINCT tenant_id, type, metric " +
"FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ?";
private static String findAllMetricsInDataBases = "SELECT DISTINCT tenant_id, type, metric " +
"FROM %s";
// Delete statement prototypes
private static String DELETE_FROM_DATA_BASE = "DELETE FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ?";
private PreparedStatement insertTenant;
private PreparedStatement insertTenantOverwrite;
private PreparedStatement findAllTenantIds;
private PreparedStatement findAllTenantIdsFromMetricsIdx;
private PreparedStatement findTenant;
private PreparedStatement insertIntoMetricsIndex;
private PreparedStatement insertIntoMetricsIndexOverwrite;
private PreparedStatement findMetricInData;
private PreparedStatement findMetricInDataCompressed;
private PreparedStatement findAllMetricsInData;
private PreparedStatement findAllMetricsInDataCompressed;
private PreparedStatement findMetricInMetricsIndex;
private PreparedStatement findAllMetricsFromTagsIndex;
private PreparedStatement getMetricTags;
private PreparedStatement getTagNames;
private PreparedStatement getTagNamesWithType;
private PreparedStatement insertCompressedData;
private PreparedStatement insertCompressedDataWithTags;
private PreparedStatement insertStringData;
private PreparedStatement insertStringDataUsingTTL;
private PreparedStatement insertStringDataWithTags;
private PreparedStatement insertStringDataWithTagsUsingTTL;
private PreparedStatement findCompressedDataByDateRangeExclusive;
private PreparedStatement findCompressedDataByDateRangeExclusiveWithLimit;
private PreparedStatement findCompressedDataByDateRangeExclusiveASC;
private PreparedStatement findCompressedDataByDateRangeExclusiveWithLimitASC;
private PreparedStatement findStringDataByDateRangeExclusive;
private PreparedStatement findStringDataByDateRangeExclusiveWithLimit;
private PreparedStatement findStringDataByDateRangeExclusiveASC;
private PreparedStatement findStringDataByDateRangeExclusiveWithLimitASC;
private PreparedStatement deleteMetricData;
private PreparedStatement deleteFromMetricRetentionIndex;
private PreparedStatement deleteMetricFromMetricsIndex;
private PreparedStatement deleteMetricDataWithLimit;
private PreparedStatement updateMetricsIndex;
private PreparedStatement addTagsToMetricsIndex;
private PreparedStatement deleteTagsFromMetricsIndex;
private PreparedStatement readMetricsIndex;
private PreparedStatement updateRetentionsIndex;
private PreparedStatement findDataRetentions;
private PreparedStatement insertMetricsTagsIndex;
private PreparedStatement deleteMetricsTagsIndex;
private PreparedStatement findMetricsByTagName;
private PreparedStatement findMetricsByTagNameValue;
private PreparedStatement updateMetricExpirationIndex;
private PreparedStatement deleteFromMetricExpirationIndex;
private PreparedStatement findMetricExpiration;
private static DateTimeFormatter TEMP_TABLE_DATEFORMATTER = (new DateTimeFormatterBuilder())
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.appendValue(ChronoField.HOUR_OF_DAY, 2).toFormatter();
private CodecRegistry codecRegistry;
private Metadata metadata;
public DataAccessImpl(Session session) {
this.session = session;
rxSession = new RxSessionImpl(session);
loadBalancingPolicy = session.getCluster().getConfiguration().getPolicies().getLoadBalancingPolicy();
codecRegistry = session.getCluster().getConfiguration().getCodecRegistry();
metadata = session.getCluster().getMetadata();
initPreparedStatements();
initializeTemporaryTableStatements();
}
/**
* Creates a key with ordinal and MetricType code for the NavigableMap.
*
* First 8 bits are reserved for the metricType code and the rest 24 bits are reserved for the ordinal
*
* @param code MetricType code
* @param ordinal TempStatement ordinal()
*
* @return Integer with those two combined
*/
private Integer getMapKey(byte code, int ordinal) {
int key = ordinal;
key |= code << 24;
return key;
}
private Integer getMapKey(MetricType type, TempStatement ts) {
return getMapKey(type.getCode(), ts.ordinal());
}
void prepareTempStatements(String tableName, Long mapKey) {
// Create an entry to the correct Long
Map<Integer, PreparedStatement> statementMap = new HashMap<>();
// Per metricType
for (MetricType<?> metricType : MetricType.userTypes()) {
if(metricType == STRING) { continue; } // We don't support String metrics in temp tables yet
for (TempStatement st : TempStatement.values()) {
Integer key = getMapKey(metricType, st);
String formatSt;
switch(st.getType()) {
case READ:
formatSt = String.format(st.getStatement(), metricTypeToColumnName(metricType),
tableName);
break;
case WRITE:
formatSt = String.format(st.getStatement(), tableName,
metricTypeToColumnName(metricType));
break;
default:
// Not supported
continue;
}
PreparedStatement prepared = session.prepare(formatSt);
statementMap.put(key, prepared);
}
}
// Untyped
for (TempStatement st : TempStatement.values()) {
Integer key = getMapKey(MetricType.UNDEFINED, st);
String formatSt;
switch(st.getType()) {
case SCAN:
case CREATE:
case DELETE:
formatSt = String.format(st.getStatement(), tableName);
break;
default:
continue;
}
PreparedStatement prepared = session.prepare(formatSt);
statementMap.put(key, prepared);
}
prepMap.put(mapKey, statementMap);
}
@Override
public Observable<ResultSet> createTempTablesIfNotExists(final Set<Long> timestamps) {
return Observable.fromCallable(() -> {
Set<String> tables = timestamps.stream()
.map(this::getTempTableName)
.collect(Collectors.toSet());
// TODO This is an IO operation..
metadata.getKeyspace(session.getLoggedKeyspace()).getTables().stream()
.map(AbstractTableMetadata::getName)
.filter(t -> t.startsWith(TEMP_TABLE_NAME_PROTOTYPE))
.forEach(tables::remove);
return tables;
})
.flatMapIterable(s -> s)
.zipWith(Observable.interval(300, TimeUnit.MILLISECONDS), (st, l) -> st)
.concatMap(this::createTemporaryTable);
}
Observable<ResultSet> createTemporaryTable(String tempTableName) {
return Observable.just(tempTableName)
.map(t -> new SimpleStatement(String.format(TempStatement.CREATE_TABLE.getStatement(), t)))
.flatMap(st -> rxSession.execute(st));
}
private void initializeTemporaryTableStatements() {
prepMap = new ConcurrentSkipListMap<>();
setTempTableCreator(new TemporaryTableStatementCreator());
boolean zeroTableExists = false;
// At startup we should initialize preparedStatements for all the temporary tables that exists
for (TableMetadata table : metadata.getKeyspace(session.getLoggedKeyspace()).getTables()) {
if(table.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
// Proceed to create the preparedStatements against this table
Long mapKey = tableToMapKey(table.getName());
prepareTempStatements(table.getName(), mapKey);
} else if(table.getName().equals(OUT_OF_ORDER_TABLE_NAME)) {
zeroTableExists = true;
}
}
if(!zeroTableExists) {
createTemporaryTable(OUT_OF_ORDER_TABLE_NAME).toBlocking().subscribe();
session.execute((String.format("ALTER TABLE %s WITH default_time_to_live = %d",
OUT_OF_ORDER_TABLE_NAME, TimeUnit.DAYS.toSeconds(7))));
session.execute((String.format("ALTER TABLE %s WITH compaction = " +
"{'compaction_window_size': '1', " +
"'compaction_window_unit': 'DAYS', " +
"'class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'}",
OUT_OF_ORDER_TABLE_NAME)));
}
// Prepare the old fashioned way (data table) as fallback when out-of-order writes happen..
// These should be transparent in writes
prepareTempStatements(OUT_OF_ORDER_TABLE_NAME, 0L); // Fall back is always at value 0 (floorKey/floorEntry will hit it)
}
private String metricTypeToColumnName(MetricType<?> type) {
switch(type.getCode()) {
case 0:
return "n_value";
case 1:
return "availability";
case 2:
return "l_value";
case 3:
return "l_value";
case 4:
return "s_value";
case 5:
return "n_value";
default:
throw new RuntimeException("Unsupported metricType");
}
}
protected void initPreparedStatements() {
insertTenant = session.prepare(
"INSERT INTO tenants (id, retentions) VALUES (?, ?) IF NOT EXISTS");
insertTenantOverwrite = session.prepare(
"INSERT INTO tenants (id, retentions) VALUES (?, ?)");
findAllTenantIds = session.prepare("SELECT DISTINCT id FROM tenants");
findAllTenantIdsFromMetricsIdx = session.prepare("SELECT DISTINCT tenant_id, type FROM metrics_idx");
findTenant = session.prepare("SELECT id, retentions FROM tenants WHERE id = ?");
findMetricInData = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? ");
findMetricInDataCompressed = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? ");
findMetricInMetricsIndex = session.prepare(
"SELECT metric, tags, data_retention " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
getMetricTags = session.prepare(
"SELECT tags " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
getTagNames = session.prepare(
"SELECT DISTINCT tenant_id, tname " +
"FROM metrics_tags_idx"); // Cassandra 3.10 will allow filtering by tenant_id
getTagNamesWithType = session.prepare(
"SELECT tenant_id, tname, type " +
"FROM metrics_tags_idx");
insertIntoMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric, data_retention, tags) " +
"VALUES (?, ?, ?, ?, ?) " +
"IF NOT EXISTS");
insertIntoMetricsIndexOverwrite = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric, data_retention, tags) " +
"VALUES (?, ?, ?, ?, ?) ");
updateMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric) VALUES (?, ?, ?)");
addTagsToMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags + ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
deleteTagsFromMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags - ?" +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
readMetricsIndex = session.prepare(
"SELECT metric, tags, data_retention " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? " +
"ORDER BY metric ASC");
findAllMetricsInData = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data");
findAllMetricsInDataCompressed = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data_compressed");
findAllMetricsFromTagsIndex = session.prepare(
"SELECT tenant_id, type, metric " +
"FROM metrics_tags_idx");
insertCompressedData = session.prepare(
"UPDATE data_compressed " +
"USING TTL ? " +
"SET c_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertCompressedDataWithTags = session.prepare(
"UPDATE data_compressed " +
"USING TTL ? " +
"SET c_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertStringData = session.prepare(
"UPDATE data " +
"SET s_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ?");
insertStringDataUsingTTL = session.prepare(
"UPDATE data " +
"USING TTL ? " +
"SET s_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ?");
insertStringDataWithTags = session.prepare(
"UPDATE data " +
"SET s_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertStringDataWithTagsUsingTTL = session.prepare(
"UPDATE data " +
"USING TTL ? " +
"SET s_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
findCompressedDataByDateRangeExclusive = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
findCompressedDataByDateRangeExclusiveWithLimit = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?" +
" LIMIT ?");
findCompressedDataByDateRangeExclusiveASC = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC");
findCompressedDataByDateRangeExclusiveWithLimitASC = session.prepare(
"SELECT time, c_value, tags FROM data_compressed" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?");
findStringDataByDateRangeExclusive = session.prepare(
"SELECT time, s_value, tags FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
findStringDataByDateRangeExclusiveWithLimit = session.prepare(
"SELECT time, s_value, tags FROM data " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?" +
" LIMIT ?");
findStringDataByDateRangeExclusiveASC = session.prepare(
"SELECT time, s_value, tags FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC");
findStringDataByDateRangeExclusiveWithLimitASC = session.prepare(
"SELECT time, s_value, tags FROM data" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?");
deleteMetricData = session.prepare(
"DELETE FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ?");
deleteMetricDataWithLimit = session.prepare(
"DELETE FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
deleteFromMetricRetentionIndex = session.prepare(
"DELETE FROM retentions_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
deleteMetricFromMetricsIndex = session.prepare(
"DELETE FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
updateRetentionsIndex = session.prepare(
"INSERT INTO retentions_idx (tenant_id, type, metric, retention) VALUES (?, ?, ?, ?)");
findDataRetentions = session.prepare(
"SELECT tenant_id, type, metric, retention " +
"FROM retentions_idx " +
"WHERE tenant_id = ? AND type = ?");
insertMetricsTagsIndex = session.prepare(
"INSERT INTO metrics_tags_idx (tenant_id, tname, tvalue, type, metric) VALUES (?, ?, ?, ?, ?)");
deleteMetricsTagsIndex = session.prepare(
"DELETE FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ? AND type = ? AND metric = ?");
findMetricsByTagName = session.prepare(
"SELECT tenant_id, type, metric, tvalue " +
"FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ?");
findMetricsByTagNameValue = session.prepare(
"SELECT tenant_id, type, metric, tvalue " +
"FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ?");
updateMetricExpirationIndex = session.prepare(
"INSERT INTO metrics_expiration_idx (tenant_id, type, metric, time) VALUES (?, ?, ?, ?)");
deleteFromMetricExpirationIndex = session.prepare(
"DELETE FROM metrics_expiration_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
findMetricExpiration = session.prepare(
"SELECT time " +
"FROM metrics_expiration_idx " +
"WHERE tenant_id = ? AND type = ? and metric = ?");
}
@Override
public Observable<ResultSet> insertTenant(Tenant tenant, boolean overwrite) {
Map<String, Integer> retentions = tenant.getRetentionSettings().entrySet().stream()
.collect(toMap(entry -> entry.getKey().getText(), Map.Entry::getValue));
if (overwrite) {
return rxSession.execute(insertTenantOverwrite.bind(tenant.getId(), retentions));
}
return rxSession.execute(insertTenant.bind(tenant.getId(), retentions));
}
@Override
public Observable<Row> findAllTenantIds() {
return rxSession.executeAndFetch(findAllTenantIds.bind())
.concatWith(rxSession.executeAndFetch(findAllTenantIdsFromMetricsIdx.bind()));
}
@Override
public Observable<Row> findTenant(String id) {
return rxSession.executeAndFetch(findTenant.bind(id));
}
@Override
public <T> ResultSetFuture insertMetricInMetricsIndex(Metric<T> metric, boolean overwrite) {
MetricId<T> metricId = metric.getMetricId();
if (overwrite) {
return session.executeAsync(
insertIntoMetricsIndexOverwrite.bind(metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), metric.getDataRetention(), metric.getTags()));
}
return session.executeAsync(insertIntoMetricsIndex.bind(metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), metric.getDataRetention(), metric.getTags()));
}
@Override
public <T> Observable<Row> findMetricInData(MetricId<T> id) {
return getPrepForAllTempTables(TempStatement.CHECK_EXISTENCE_OF_METRIC_IN_TABLE)
.map(b -> b.bind(id.getTenantId(), id.getType().getCode(), id.getName()))
.flatMap(b -> rxSession.executeAndFetch(b))
.concatWith(rxSession.executeAndFetch(findMetricInData
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART))
.concatWith(
rxSession.executeAndFetch(findMetricInDataCompressed
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART))))
.take(1);
}
@Override
public <T> Observable<Row> findMetricInMetricsIndex(MetricId<T> id) {
return rxSession.executeAndFetch(findMetricInMetricsIndex
.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<Row> getMetricTags(MetricId<T> id) {
return rxSession.executeAndFetch(getMetricTags.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public Observable<Row> getTagNames() {
return rxSession.executeAndFetch(getTagNames.bind());
}
@Override
public Observable<Row> getTagNamesWithType() {
return rxSession.executeAndFetch(getTagNamesWithType.bind());
}
@Override
public <T> Observable<ResultSet> addTags(Metric<T> metric, Map<String, String> tags) {
MetricId<T> metricId = metric.getMetricId();
BoundStatement stmt = addTagsToMetricsIndex.bind(tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName());
return rxSession.execute(stmt);
}
@Override
public <T> Observable<ResultSet> deleteTags(Metric<T> metric, Set<String> tags) {
MetricId<T> metricId = metric.getMetricId();
BoundStatement stmt = deleteTagsFromMetricsIndex.bind(tags, metricId.getTenantId(),
metricId.getType().getCode(), metricId.getName());
return rxSession.execute(stmt);
}
@Override
public <T> Observable<Integer> updateMetricsIndex(Observable<Metric<T>> metrics) {
return metrics.map(Metric::getMetricId)
.map(id -> updateMetricsIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()))
.compose(new BatchStatementTransformer())
.flatMap(batch -> rxSession.execute(batch).map(resultSet -> batch.size()));
}
@Override
public <T> Observable<Row> findMetricsInMetricsIndex(String tenantId, MetricType<T> type) {
return rxSession.executeAndFetch(readMetricsIndex.bind(tenantId, type.getCode()));
}
/**
* Fetch all the data from a temporary table for the compression job. Using TokenRanges avoids fetching first
* all the metrics' partition keys and then requesting them.
*
* Performance can be improved by using data locality and fetching with multiple threads.
*
* @param timestamp A timestamp inside the wanted bucket (such as the previous starting row timestamp)
* @param pageSize How many rows to fetch each time
* @param maxConcurrency To how many streams should token ranges be split to
* @return Observable of Observables per partition key
*/
@Override
public Observable<Observable<Row>> findAllDataFromBucket(long timestamp, int pageSize, int maxConcurrency) {
PreparedStatement ts =
getTempStatement(MetricType.UNDEFINED, TempStatement.SCAN_WITH_TOKEN_RANGES, timestamp);
// The table does not exists - case such as when starting Hawkular-Metrics for the first time just before
// compression kicks in.
if(ts == null || prepMap.floorKey(timestamp) == 0L) {
return Observable.empty();
}
return Observable.from(getTokenRanges())
.map(tr -> rxSession.executeAndFetch(
getTempStatement(MetricType.UNDEFINED, TempStatement.SCAN_WITH_TOKEN_RANGES, timestamp)
.bind()
.setToken(0, tr.getStart())
.setToken(1, tr.getEnd())
.setFetchSize(pageSize)));
}
private Set<TokenRange> getTokenRanges() {
Set<TokenRange> tokenRanges = new HashSet<>();
for (TokenRange tokenRange : metadata.getTokenRanges()) {
tokenRanges.addAll(tokenRange.unwrap());
}
return tokenRanges;
}
@Override
public Observable<ResultSet> dropTempTable(long timestamp) {
String fullTableName = getTempTableName(timestamp);
String dropCQL = String.format("DROP TABLE IF EXISTS %s", fullTableName);
return rxSession.execute(dropCQL);
}
private Observable<PreparedStatement> getPrepForAllTempTables(TempStatement ts) {
return Observable.from(prepMap.entrySet())
.map(Map.Entry::getValue)
.map(pMap -> pMap.get(getMapKey(MetricType.UNDEFINED, ts)));
}
@Override
public Observable<Row> findAllMetricIdentifiersInData() {
return getPrepForAllTempTables(TempStatement.LIST_ALL_METRICS_FROM_TABLE)
.flatMap(b -> rxSession.executeAndFetch(b.bind()))
.mergeWith(rxSession.executeAndFetch(findAllMetricsInData.bind()))
.mergeWith(rxSession.executeAndFetch(findAllMetricsInDataCompressed.bind()));
}
/*
* Applies micro-batching capabilities by taking advantage of token ranges in the Cassandra
*/
private Observable.Transformer<BoundStatement, Integer> applyMicroBatching() {
return tObservable -> tObservable
.groupBy(b -> {
ByteBuffer routingKey = b.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED,
codecRegistry);
Token token = metadata.newToken(routingKey);
for (TokenRange tokenRange : session.getCluster().getMetadata().getTokenRanges()) {
if (tokenRange.contains(token)) {
return tokenRange;
}
}
log.warn("Unable to find any Cassandra node to insert token " + token.toString());
return session.getCluster().getMetadata().getTokenRanges().iterator().next();
})
.flatMap(g -> g.compose(new BoundBatchStatementTransformer()))
.flatMap(batch -> rxSession
.execute(batch)
.compose(applyInsertRetryPolicy())
.map(resultSet -> batch.size())
);
}
/*
* Apply our current retry policy to the insert behavior
*/
private <T> Observable.Transformer<T, T> applyInsertRetryPolicy() {
return tObservable -> tObservable
.retryWhen(errors -> {
Observable<Integer> range = Observable.range(1, 2);
return errors
.zipWith(range, (t, i) -> {
if (t instanceof DriverException) {
return i;
}
throw Exceptions.propagate(t);
})
.flatMap(retryCount -> {
long delay = (long) Math.min(Math.pow(2, retryCount) * 1000, 3000);
log.debug("Retrying batch insert in " + delay + " ms");
return Observable.timer(delay, TimeUnit.MILLISECONDS);
});
});
}
Long tableToMapKey(String tableName) {
LocalDateTime parsed = LocalDateTime
.parse(tableName.substring(TEMP_TABLE_NAME_PROTOTYPE.length()),
TEMP_TABLE_DATEFORMATTER);
return Long.valueOf(parsed.toInstant(ZoneOffset.UTC).toEpochMilli());
}
String getTempTableName(long timestamp) {
return String.format(TEMP_TABLE_NAME_FORMAT_STRING,
ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), UTC)
.with(DateTimeService.startOfPreviousEvenHour())
.format(TEMP_TABLE_DATEFORMATTER));
}
PreparedStatement getTempStatement(MetricType type, TempStatement ts, long timestamp) {
Map.Entry<Long, Map<Integer, PreparedStatement>> floorEntry = prepMap
.floorEntry(timestamp);
if(floorEntry != null) {
return floorEntry.getValue()
.get(getMapKey(type, ts));
}
return null;
}
@Override
public <T> Observable<Integer> insertData(Observable<Metric<T>> metrics) {
return metrics
.flatMap(m -> Observable.from(m.getDataPoints())
.compose(mapTempInsertStatement(m)))
.compose(applyMicroBatching());
}
@SuppressWarnings("unchecked")
private <T> Observable.Transformer<DataPoint<T>, BoundStatement> mapTempInsertStatement(Metric<T> metric) {
MetricType<T> type = metric.getMetricId().getType();
MetricId<T> metricId = metric.getMetricId();
return tO -> tO
.map(dataPoint -> {
BoundStatement bs;
int i = 1;
PreparedStatement st;
if (dataPoint.getTags().isEmpty()) {
st = getTempStatement(type, TempStatement.INSERT_DATA, dataPoint.getTimestamp());
if(st == null) {
return null;
}
bs = st.bind();
} else {
st = getTempStatement(type, TempStatement.INSERT_DATA_WITH_TAGS, dataPoint.getTimestamp());
if(st == null) {
return null;
}
bs = st.bind();
bs.setMap(1, dataPoint.getTags());
i++;
}
bindValue(bs, type, dataPoint);
return bs
.setString(i, metricId.getTenantId())
.setByte(++i, metricId.getType().getCode())
.setString(++i, metricId.getName())
.setTimestamp(++i, new Date(dataPoint.getTimestamp()));
})
.filter(Objects::nonNull);
}
private <T> void bindValue(BoundStatement bs, MetricType<T> type, DataPoint<T> dataPoint) {
switch(type.getCode()) {
case 0:
bs.setDouble(0, (Double) dataPoint.getValue());
break;
case 1:
bs.setBytes(0, getBytes((DataPoint<AvailabilityType>) dataPoint));
break;
case 2:
bs.setLong(0, (Long) dataPoint.getValue());
break;
case 3:
bs.setLong(0, (Long) dataPoint.getValue());
break;
case 4:
throw new IllegalArgumentException("Not implemented yet");
case 5:
bs.setDouble(0, (Double) dataPoint.getValue());
break;
default:
throw new IllegalArgumentException("Unsupported metricType");
}
}
private Observable.Transformer<DataPoint<String>, BoundStatement> mapStringDatapoint(Metric<String> metric, int
ttl, int maxSize) {
return tObservable -> tObservable
.map(dataPoint -> {
if (maxSize != -1 && dataPoint.getValue().length() > maxSize) {
throw new IllegalArgumentException(dataPoint + " exceeds max string length of " + maxSize +
" characters");
}
if (dataPoint.getTags().isEmpty()) {
if (ttl >= 0) {
return bindDataPoint(insertStringDataUsingTTL, metric, dataPoint.getValue(),
dataPoint.getTimestamp(), ttl);
} else {
return bindDataPoint(insertStringData, metric, dataPoint.getValue(),
dataPoint.getTimestamp());
}
} else {
if (ttl >= 0) {
return bindDataPoint(insertStringDataWithTagsUsingTTL, metric, dataPoint.getValue(),
dataPoint.getTags(), dataPoint.getTimestamp(), ttl);
} else {
return bindDataPoint(insertStringDataWithTags, metric, dataPoint.getValue(),
dataPoint.getTags(), dataPoint.getTimestamp());
}
}
});
}
@Override
public Observable<Integer> insertStringDatas(Observable<Metric<String>> strings,
Function<MetricId<String>, Integer> ttlFetcher, int maxSize) {
return strings
.flatMap(string -> {
int ttl = ttlFetcher.apply(string.getMetricId());
return Observable.from(string.getDataPoints())
.compose(mapStringDatapoint(string, ttl, maxSize));
}
)
.compose(applyMicroBatching());
}
@Override
public Observable<Integer> insertStringData(Metric<String> metric, int maxSize) {
return insertStringData(metric, -1, maxSize);
}
@Override
public Observable<Integer> insertStringData(Metric<String> metric, int ttl, int maxSize) {
return Observable.from(metric.getDataPoints())
.compose(mapStringDatapoint(metric, ttl, maxSize))
.compose(new BatchStatementTransformer())
.flatMap(batch -> rxSession.execute(batch).map(resultSet -> batch.size()));
}
// TODO These are only used by the String methods
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value, long timestamp) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(value, metricId.getTenantId(), metricId.getType().getCode(), metricId.getName(),
DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value, long timestamp,
int ttl) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(ttl, value, metricId.getTenantId(), metricId.getType().getCode(), metricId.getName(),
DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value,
Map<String, String> tags, long timestamp) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(value, tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value,
Map<String, String> tags, long timestamp, int ttl) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(ttl, value, tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), DPART, getTimeUUID(timestamp));
}
@Override
public Observable<Row> findCompressedData(MetricId<?> id, long startTime, long endTime, int limit, Order
order) {
if (order == Order.ASC) {
if (limit <= 0) {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveASC.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime)));
} else {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveWithLimitASC.bind(
id.getTenantId(), id.getType().getCode(), id.getName(), DPART, new Date(startTime),
new Date(endTime), limit));
}
} else {
if (limit <= 0) {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusive.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime)));
} else {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveWithLimit.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime),
limit));
}
}
}
private SortedMap<Long, Map<Integer, PreparedStatement>> subSetMap(long startTime, long endTime, Order order) {
Long startKey = prepMap.floorKey(startTime);
Long endKey = prepMap.floorKey(endTime);
// The start time is already compressed, start the request from earliest non-compressed
if(startKey == null) {
startKey = prepMap.ceilingKey(startTime);
}
// Just in case even the end is in the past
if(endKey == null) {
endKey = startKey;
}
// Depending on the order, these must be read in the correct order also..
SortedMap<Long, Map<Integer, PreparedStatement>> statementMap;
if(order == Order.ASC) {
statementMap = prepMap.subMap(startKey, true, endKey,
true);
} else {
statementMap = new ConcurrentSkipListMap<>((var0, var2) -> var0 < var2?1:(var0 == var2?0:-1));
statementMap.putAll(prepMap.subMap(startKey, true, endKey, true));
}
return statementMap;
}
@Override
public <T> Observable<Row> findTempData(MetricId<T> id, long startTime, long endTime, int limit, Order order,
int pageSize) {
MetricType<T> type = id.getType();
SortedMap<Long, Map<Integer, PreparedStatement>> statementMap = subSetMap(startTime, endTime, order);
Observable<Map<Integer, PreparedStatement>> buckets = Observable.from(statementMap.values());
if (order == Order.ASC) {
if (limit <= 0) {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dataByDateRangeExclusiveASC)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(),
new Date(startTime), new Date(endTime))
.setFetchSize(pageSize)));
} else {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dataByDateRangeExclusiveWithLimitASC)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime),
new Date(endTime), limit)
.setFetchSize(pageSize)));
}
} else {
if (limit <= 0) {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dateRangeExclusive)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime),
new Date(endTime))
.setFetchSize(pageSize)));
} else {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dateRangeExclusiveWithLimit)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime), new Date(endTime),
limit)
.setFetchSize(pageSize)));
}
}
}
@Override
public Observable<Row> findStringData(MetricId<String> id, long startTime, long endTime, int limit, Order order,
int pageSize) {
if (order == Order.ASC) {
if (limit <= 0) {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveASC.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime))
.setFetchSize(pageSize));
} else {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveWithLimitASC.bind(
id.getTenantId(), STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime),
getTimeUUID(endTime), limit).setFetchSize(pageSize));
}
} else {
if (limit <= 0) {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusive.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime))
.setFetchSize(pageSize));
} else {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveWithLimit.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime),
limit).setFetchSize(pageSize));
}
}
}
@Override
public <T> Observable<ResultSet> deleteMetricData(MetricId<T> id) {
if(id.getType() == STRING) {
return rxSession.execute(deleteMetricData.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART));
}
return getPrepForAllTempTables(TempStatement.DELETE_DATA)
.flatMap(p -> rxSession.execute(p.bind(id.getTenantId(), id.getType().getCode(), id.getName())));
}
@Override
public <T> Observable<ResultSet> deleteMetricFromRetentionIndex(MetricId<T> id) {
return rxSession
.execute(deleteFromMetricRetentionIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<ResultSet> deleteMetricFromMetricsIndex(MetricId<T> id) {
return rxSession
.execute(deleteMetricFromMetricsIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
private ByteBuffer getBytes(DataPoint<AvailabilityType> dataPoint) {
return ByteBuffer.wrap(new byte[]{dataPoint.getValue().getCode()});
}
@Override
public <T> ResultSetFuture findDataRetentions(String tenantId, MetricType<T> type) {
return session.executeAsync(findDataRetentions.bind(tenantId, type.getCode()));
}
@Override
public <T> Observable<ResultSet> updateRetentionsIndex(String tenantId, MetricType<T> type,
Map<String, Integer> retentions) {
return Observable.from(retentions.entrySet())
.map(entry -> updateRetentionsIndex.bind(tenantId, type.getCode(), entry.getKey(), entry.getValue()))
.compose(new BatchStatementTransformer())
.flatMap(rxSession::execute);
}
@Override
public <T> Observable<ResultSet> insertIntoMetricsTagsIndex(Metric<T> metric, Map<String, String> tags) {
MetricId<T> metricId = metric.getMetricId();
return tagsUpdates(tags, (name, value) -> insertMetricsTagsIndex.bind(metricId.getTenantId(), name, value,
metricId.getType().getCode(), metricId.getName()));
}
@Override
public <T> Observable<ResultSet> deleteFromMetricsTagsIndex(MetricId<T> id, Map<String, String> tags) {
return tagsUpdates(tags, (name, value) -> deleteMetricsTagsIndex.bind(id.getTenantId(), name, value,
id.getType().getCode(), id.getName()));
}
private Observable<ResultSet> tagsUpdates(Map<String, String> tags,
BiFunction<String, String, BoundStatement> bindVars) {
return Observable.from(tags.entrySet())
.map(entry -> bindVars.apply(entry.getKey(), entry.getValue()))
.flatMap(rxSession::execute);
}
@Override
public Observable<Row> findMetricsByTagName(String tenantId, String tag) {
return rxSession.executeAndFetch(findMetricsByTagName.bind(tenantId, tag));
}
@Override
public Observable<Row> findMetricsByTagNameValue(String tenantId, String tag, String tvalue) {
return rxSession.executeAndFetch(findMetricsByTagNameValue.bind(tenantId, tag, tvalue));
}
@Override
public <T> ResultSetFuture updateRetentionsIndex(Metric<T> metric) {
return session.executeAsync(updateRetentionsIndex.bind(metric.getMetricId().getTenantId(),
metric.getMetricId().getType().getCode(), metric.getMetricId().getName(), metric.getDataRetention()));
}
@Override
public <T> Observable<ResultSet> insertCompressedData(MetricId<T> id, long timeslice,
CompressedPointContainer cpc, int ttl) {
// ByteBuffer position must be 0!
Observable.just(cpc.getValueBuffer(), cpc.getTimestampBuffer(), cpc.getTagsBuffer())
.doOnNext(bb -> {
if(bb != null && bb.position() != 0) {
bb.rewind();
}
});
BiConsumer<BoundStatement, Integer> mapper = (b, i) -> {
b.setString(i, id.getTenantId())
.setByte(i+1, id.getType().getCode())
.setString(i+2, id.getName())
.setLong(i+3, DPART)
.setTimestamp(i+4, new Date(timeslice));
};
BoundStatement b;
int i = 0;
if(cpc.getTagsBuffer() != null) {
b = insertCompressedDataWithTags.bind()
.setInt(i, ttl)
.setBytes(i+1, cpc.getValueBuffer())
.setBytes(i+2, cpc.getTagsBuffer());
mapper.accept(b, 3);
} else {
b = insertCompressedData.bind()
.setInt(i, ttl)
.setBytes(i+1, cpc.getValueBuffer());
mapper.accept(b, 2);
}
return rxSession.execute(b);
}
@Override
public <T> Observable<ResultSet> deleteAndInsertCompressedGauge(MetricId<T> id, long timeslice,
CompressedPointContainer cpc,
long sliceStart, long sliceEnd, int ttl) {
return Observable.just(deleteMetricDataWithLimit.bind()
.setString(0, id.getTenantId())
.setByte(1, id.getType().getCode())
.setString(2, id.getName())
.setLong(3, DPART)
.setUUID(4, getTimeUUID(sliceStart))
.setUUID(5, getTimeUUID(sliceEnd)))
.concatMap(st -> rxSession.execute(st))
.concatWith(insertCompressedData(id, timeslice, cpc, ttl));
}
@Override
public Observable<Row> findAllMetricsFromTagsIndex() {
return rxSession.executeAndFetch(findAllMetricsFromTagsIndex.bind());
}
@Override
public <T> Observable<ResultSet> updateMetricExpirationIndex(MetricId<T> id, long expirationTime) {
return rxSession.execute(updateMetricExpirationIndex.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), new Date(expirationTime)));
}
@Override
public <T> Observable<ResultSet> deleteFromMetricExpirationIndex(MetricId<T> id) {
return rxSession
.execute(deleteFromMetricExpirationIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<Row> findMetricExpiration(MetricId<T> id) {
return rxSession
.executeAndFetch(findMetricExpiration.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
private class TemporaryTableStatementCreator implements SchemaChangeListener {
private final CoreLogger log = CoreLogging.getCoreLogger(TemporaryTableStatementCreator.class);
@Override
public void onTableAdded(TableMetadata tableMetadata) {
log.debugf("Table added %s", tableMetadata.getName());
if(tableMetadata.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
log.debugf("Registering prepared statements for table %s", tableMetadata.getName());
Observable.fromCallable(() -> {
prepareTempStatements(tableMetadata.getName(), tableToMapKey(tableMetadata.getName()));
return null;
})
.subscribeOn(Schedulers.io())
.subscribe();
}
}
@Override
public void onTableRemoved(TableMetadata tableMetadata) {
if(tableMetadata.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
log.debugf("Removing prepared statements for table %s", tableMetadata.getName());
removeTempStatements(tableMetadata.getName());
}
}
// Rest are not interesting to us
@Override public void onKeyspaceAdded(KeyspaceMetadata keyspaceMetadata) {}
@Override public void onKeyspaceRemoved(KeyspaceMetadata keyspaceMetadata) {}
@Override public void onKeyspaceChanged(KeyspaceMetadata keyspaceMetadata, KeyspaceMetadata keyspaceMetadata1) {}
@Override public void onTableChanged(TableMetadata tableMetadata, TableMetadata tableMetadata1) {
}
@Override public void onUserTypeAdded(UserType userType) {}
@Override public void onUserTypeRemoved(UserType userType) {}
@Override public void onUserTypeChanged(UserType userType, UserType userType1) {}
@Override public void onFunctionAdded(FunctionMetadata functionMetadata) {}
@Override public void onFunctionRemoved(FunctionMetadata functionMetadata) {}
@Override public void onFunctionChanged(FunctionMetadata functionMetadata, FunctionMetadata functionMetadata1) {}
@Override public void onAggregateAdded(AggregateMetadata aggregateMetadata) {}
@Override public void onAggregateRemoved(AggregateMetadata aggregateMetadata) {}
@Override public void onAggregateChanged(AggregateMetadata aggregateMetadata, AggregateMetadata aggregateMetadata1) {}
@Override public void onMaterializedViewAdded(MaterializedViewMetadata materializedViewMetadata) {}
@Override public void onMaterializedViewRemoved(MaterializedViewMetadata materializedViewMetadata) {}
@Override public void onMaterializedViewChanged(MaterializedViewMetadata materializedViewMetadata,
MaterializedViewMetadata materializedViewMetadata1) {}
@Override public void onRegister(Cluster cluster) {}
@Override public void onUnregister(Cluster cluster) {}
}
void removeTempStatements(String tableName) {
// Find the integer key and remove from prepMap
Long mapKey = tableToMapKey(tableName);
prepMap.remove(mapKey);
}
@Override public void shutdown() {
session.getCluster().unregister(tableCreator);
tableCreator = null;
}
public void setTempTableCreator(TemporaryTableStatementCreator creator) {
if(tableCreator != null) {
session.getCluster().unregister(tableCreator);
}
tableCreator = creator;
session.getCluster().register(tableCreator);
}
}
| core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/DataAccessImpl.java | /*
* Copyright 2014-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.core.service;
import static java.time.ZoneOffset.UTC;
import static java.util.stream.Collectors.toMap;
import static org.hawkular.metrics.core.service.TimeUUIDUtils.getTimeUUID;
import static org.hawkular.metrics.model.MetricType.STRING;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.hawkular.metrics.core.service.compress.CompressedPointContainer;
import org.hawkular.metrics.core.service.log.CoreLogger;
import org.hawkular.metrics.core.service.log.CoreLogging;
import org.hawkular.metrics.core.service.transformers.BatchStatementTransformer;
import org.hawkular.metrics.core.service.transformers.BoundBatchStatementTransformer;
import org.hawkular.metrics.datetime.DateTimeService;
import org.hawkular.metrics.model.AvailabilityType;
import org.hawkular.metrics.model.DataPoint;
import org.hawkular.metrics.model.Metric;
import org.hawkular.metrics.model.MetricId;
import org.hawkular.metrics.model.MetricType;
import org.hawkular.metrics.model.Tenant;
import org.hawkular.rx.cassandra.driver.RxSession;
import org.hawkular.rx.cassandra.driver.RxSessionImpl;
import com.datastax.driver.core.AbstractTableMetadata;
import com.datastax.driver.core.AggregateMetadata;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.CodecRegistry;
import com.datastax.driver.core.FunctionMetadata;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.MaterializedViewMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.SchemaChangeListener;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SimpleStatement;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.Token;
import com.datastax.driver.core.TokenRange;
import com.datastax.driver.core.UserType;
import com.datastax.driver.core.exceptions.DriverException;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import rx.Observable;
import rx.exceptions.Exceptions;
import rx.schedulers.Schedulers;
/**
*
* @author John Sanda
*/
public class DataAccessImpl implements DataAccess {
private static final CoreLogger log = CoreLogging.getCoreLogger(DataAccessImpl.class);
public static final String OUT_OF_ORDER_TABLE_NAME = "data_0";
public static final String TEMP_TABLE_NAME_PROTOTYPE = "data_temp_";
public static final String TEMP_TABLE_NAME_FORMAT_STRING = TEMP_TABLE_NAME_PROTOTYPE + "%s";
public static final long DPART = 0;
private Session session;
private RxSession rxSession;
private LoadBalancingPolicy loadBalancingPolicy;
// Turn to MetricType agnostic
// See getMapKey(byte, int)
private NavigableMap<Long, Map<Integer, PreparedStatement>> prepMap;
// TODO Move all of these to a new class (Cassandra specific temp table) to allow multiple implementations (such
// as in-memory + WAL in Cassandra)
private TemporaryTableStatementCreator tableCreator = null;
private enum StatementType {
READ, WRITE, SCAN, CREATE, DELETE
}
private enum TempStatement {
// Should I map these to something else..? More like a key to the actual statement
dateRangeExclusive(byDateRangeExclusiveBase, StatementType.READ),
dateRangeExclusiveWithLimit(dateRangeExclusiveWithLimitBase, StatementType.READ),
dataByDateRangeExclusiveASC(dataByDateRangeExclusiveASCBase, StatementType.READ),
dataByDateRangeExclusiveWithLimitASC(dataByDateRangeExclusiveWithLimitASCBase, StatementType.READ),
SCAN_WITH_TOKEN_RANGES(scanTableBase, StatementType.SCAN),
CHECK_EXISTENCE_OF_METRIC_IN_TABLE(findMetricInDataBase, StatementType.SCAN),
LIST_ALL_METRICS_FROM_TABLE(findAllMetricsInDataBases, StatementType.SCAN),
INSERT_DATA(data, StatementType.WRITE),
INSERT_DATA_WITH_TAGS(dataWithTags, StatementType.WRITE),
CREATE_TABLE(TEMP_TABLE_BASE_CREATE, StatementType.CREATE),
// CREATE_WAL(TEMP_TABLE_WAL_CREATE, StatementType.CREATE);
DELETE_DATA(DELETE_FROM_DATA_BASE, StatementType.DELETE);
private final String statement;
private StatementType type;
TempStatement(String st, StatementType t) {
statement = st;
type = t;
}
public String getStatement() {
return statement;
}
public StatementType getType() {
return type;
}
}
// Read statement prototypes
private static String byDateRangeExclusiveBase =
"SELECT time, %s, tags FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ? AND time < ?";
private static String dateRangeExclusiveWithLimitBase =
"SELECT time, %s, tags FROM %s " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ? AND time < ?" +
" LIMIT ?";
private static String dataByDateRangeExclusiveASCBase =
"SELECT time, %s, tags FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC";
private static String dataByDateRangeExclusiveWithLimitASCBase =
"SELECT time, %s, tags FROM %s" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?";
private static String scanTableBase =
"SELECT tenant_id, type, metric, time, n_value, availability, l_value, tags, token(tenant_id, type, " +
"metric) FROM %s " +
"WHERE token(tenant_id, type, metric) > ? AND token(tenant_id, type, metric) <=" +
" ?";
// Create statement prototype
private static String TEMP_TABLE_BASE_CREATE = "CREATE TABLE %s ( " +
"tenant_id text, " +
"type tinyint, " +
"metric text, " +
"time timestamp, " +
"n_value double, " +
"availability blob, " +
"l_value bigint, " +
"tags map<text,text>, " +
"PRIMARY KEY ((tenant_id, type, metric), time)" +
") WITH CLUSTERING ORDER BY (time DESC)";
// For in-memory buffering
/*
private static String TEMP_TABLE_WAL_CREATE = "CREATE TABLE %s (" +
"tenant_id text, " +
"type tinyint, " +
"metric text, " +
"dpart bigint, " +
"time timestamp, " +
"count int, " +
"value blob, " +
"tags blob, " +
"PRIMARY KEY ((tenant_id, type, metric), time) " +
") WITH CLUSTERING ORDER BY (time DESC)";
*/
// Insert statement prototypes
private static String data = "UPDATE %s " +
"SET %s = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time = ? ";
private static String dataWithTags = "UPDATE %s " +
"SET %s = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND time = ? ";
// Metric definition prototypes
private static String findMetricInDataBase = "SELECT DISTINCT tenant_id, type, metric " +
"FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ?";
private static String findAllMetricsInDataBases = "SELECT DISTINCT tenant_id, type, metric " +
"FROM %s";
// Delete statement prototypes
private static String DELETE_FROM_DATA_BASE = "DELETE FROM %s " +
"WHERE tenant_id = ? AND type = ? AND metric = ?";
private PreparedStatement insertTenant;
private PreparedStatement insertTenantOverwrite;
private PreparedStatement findAllTenantIds;
private PreparedStatement findAllTenantIdsFromMetricsIdx;
private PreparedStatement findTenant;
private PreparedStatement insertIntoMetricsIndex;
private PreparedStatement insertIntoMetricsIndexOverwrite;
private PreparedStatement findMetricInData;
private PreparedStatement findMetricInDataCompressed;
private PreparedStatement findAllMetricsInData;
private PreparedStatement findAllMetricsInDataCompressed;
private PreparedStatement findMetricInMetricsIndex;
private PreparedStatement findAllMetricsFromTagsIndex;
private PreparedStatement getMetricTags;
private PreparedStatement getTagNames;
private PreparedStatement getTagNamesWithType;
private PreparedStatement insertCompressedData;
private PreparedStatement insertCompressedDataWithTags;
private PreparedStatement insertStringData;
private PreparedStatement insertStringDataUsingTTL;
private PreparedStatement insertStringDataWithTags;
private PreparedStatement insertStringDataWithTagsUsingTTL;
private PreparedStatement findCompressedDataByDateRangeExclusive;
private PreparedStatement findCompressedDataByDateRangeExclusiveWithLimit;
private PreparedStatement findCompressedDataByDateRangeExclusiveASC;
private PreparedStatement findCompressedDataByDateRangeExclusiveWithLimitASC;
private PreparedStatement findStringDataByDateRangeExclusive;
private PreparedStatement findStringDataByDateRangeExclusiveWithLimit;
private PreparedStatement findStringDataByDateRangeExclusiveASC;
private PreparedStatement findStringDataByDateRangeExclusiveWithLimitASC;
private PreparedStatement deleteMetricData;
private PreparedStatement deleteFromMetricRetentionIndex;
private PreparedStatement deleteMetricFromMetricsIndex;
private PreparedStatement deleteMetricDataWithLimit;
private PreparedStatement updateMetricsIndex;
private PreparedStatement addTagsToMetricsIndex;
private PreparedStatement deleteTagsFromMetricsIndex;
private PreparedStatement readMetricsIndex;
private PreparedStatement updateRetentionsIndex;
private PreparedStatement findDataRetentions;
private PreparedStatement insertMetricsTagsIndex;
private PreparedStatement deleteMetricsTagsIndex;
private PreparedStatement findMetricsByTagName;
private PreparedStatement findMetricsByTagNameValue;
private PreparedStatement updateMetricExpirationIndex;
private PreparedStatement deleteFromMetricExpirationIndex;
private PreparedStatement findMetricExpiration;
private static DateTimeFormatter TEMP_TABLE_DATEFORMATTER = (new DateTimeFormatterBuilder())
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.appendValue(ChronoField.HOUR_OF_DAY, 2).toFormatter();
private CodecRegistry codecRegistry;
private Metadata metadata;
public DataAccessImpl(Session session) {
this.session = session;
rxSession = new RxSessionImpl(session);
loadBalancingPolicy = session.getCluster().getConfiguration().getPolicies().getLoadBalancingPolicy();
codecRegistry = session.getCluster().getConfiguration().getCodecRegistry();
metadata = session.getCluster().getMetadata();
initPreparedStatements();
initializeTemporaryTableStatements();
}
/**
* Creates a key with ordinal and MetricType code for the NavigableMap.
*
* First 8 bits are reserved for the metricType code and the rest 24 bits are reserved for the ordinal
*
* @param code MetricType code
* @param ordinal TempStatement ordinal()
*
* @return Integer with those two combined
*/
private Integer getMapKey(byte code, int ordinal) {
int key = ordinal;
key |= code << 24;
return key;
}
private Integer getMapKey(MetricType type, TempStatement ts) {
return getMapKey(type.getCode(), ts.ordinal());
}
void prepareTempStatements(String tableName, Long mapKey) {
// Create an entry to the correct Long
Map<Integer, PreparedStatement> statementMap = new HashMap<>();
// Per metricType
for (MetricType<?> metricType : MetricType.userTypes()) {
if(metricType == STRING) { continue; } // We don't support String metrics in temp tables yet
for (TempStatement st : TempStatement.values()) {
Integer key = getMapKey(metricType, st);
String formatSt;
switch(st.getType()) {
case READ:
formatSt = String.format(st.getStatement(), metricTypeToColumnName(metricType),
tableName);
break;
case WRITE:
formatSt = String.format(st.getStatement(), tableName,
metricTypeToColumnName(metricType));
break;
default:
// Not supported
continue;
}
PreparedStatement prepared = session.prepare(formatSt);
statementMap.put(key, prepared);
}
}
// Untyped
for (TempStatement st : TempStatement.values()) {
Integer key = getMapKey(MetricType.UNDEFINED, st);
String formatSt;
switch(st.getType()) {
case SCAN:
case CREATE:
case DELETE:
formatSt = String.format(st.getStatement(), tableName);
break;
default:
continue;
}
PreparedStatement prepared = session.prepare(formatSt);
statementMap.put(key, prepared);
}
prepMap.put(mapKey, statementMap);
}
@Override
public Observable<ResultSet> createTempTablesIfNotExists(final Set<Long> timestamps) {
return Observable.fromCallable(() -> {
Set<String> tables = timestamps.stream()
.map(this::getTempTableName)
.collect(Collectors.toSet());
// TODO This is an IO operation..
metadata.getKeyspace(session.getLoggedKeyspace()).getTables().stream()
.map(AbstractTableMetadata::getName)
.filter(t -> t.startsWith(TEMP_TABLE_NAME_PROTOTYPE))
.forEach(tables::remove);
return tables;
})
.flatMapIterable(s -> s)
.zipWith(Observable.interval(300, TimeUnit.MILLISECONDS), (st, l) -> st)
.concatMap(this::createTemporaryTable);
}
Observable<ResultSet> createTemporaryTable(String tempTableName) {
return Observable.just(tempTableName)
.map(t -> new SimpleStatement(String.format(TempStatement.CREATE_TABLE.getStatement(), t)))
.flatMap(st -> rxSession.execute(st));
}
private void initializeTemporaryTableStatements() {
prepMap = new ConcurrentSkipListMap<>();
setTempTableCreator(new TemporaryTableStatementCreator());
boolean zeroTableExists = false;
// At startup we should initialize preparedStatements for all the temporary tables that exists
for (TableMetadata table : metadata.getKeyspace(session.getLoggedKeyspace()).getTables()) {
if(table.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
// Proceed to create the preparedStatements against this table
Long mapKey = tableToMapKey(table.getName());
prepareTempStatements(table.getName(), mapKey);
} else if(table.getName().equals(OUT_OF_ORDER_TABLE_NAME)) {
zeroTableExists = true;
}
}
if(!zeroTableExists) {
createTemporaryTable(OUT_OF_ORDER_TABLE_NAME).toBlocking().subscribe();
session.execute((String.format("ALTER TABLE %s WITH default_time_to_live = %d",
OUT_OF_ORDER_TABLE_NAME, TimeUnit.DAYS.toSeconds(7))));
session.execute((String.format("ALTER TABLE %s WITH compaction = " +
"{'compaction_window_size': '1', " +
"'compaction_window_unit': 'DAYS', " +
"'class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'}",
OUT_OF_ORDER_TABLE_NAME)));
}
// Prepare the old fashioned way (data table) as fallback when out-of-order writes happen..
// These should be transparent in writes
prepareTempStatements(OUT_OF_ORDER_TABLE_NAME, 0L); // Fall back is always at value 0 (floorKey/floorEntry will hit it)
}
private String metricTypeToColumnName(MetricType<?> type) {
switch(type.getCode()) {
case 0:
return "n_value";
case 1:
return "availability";
case 2:
return "l_value";
case 3:
return "l_value";
case 4:
return "s_value";
case 5:
return "n_value";
default:
throw new RuntimeException("Unsupported metricType");
}
}
protected void initPreparedStatements() {
insertTenant = session.prepare(
"INSERT INTO tenants (id, retentions) VALUES (?, ?) IF NOT EXISTS");
insertTenantOverwrite = session.prepare(
"INSERT INTO tenants (id, retentions) VALUES (?, ?)");
findAllTenantIds = session.prepare("SELECT DISTINCT id FROM tenants");
findAllTenantIdsFromMetricsIdx = session.prepare("SELECT DISTINCT tenant_id, type FROM metrics_idx");
findTenant = session.prepare("SELECT id, retentions FROM tenants WHERE id = ?");
findMetricInData = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? ");
findMetricInDataCompressed = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? ");
findMetricInMetricsIndex = session.prepare(
"SELECT metric, tags, data_retention " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
getMetricTags = session.prepare(
"SELECT tags " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
getTagNames = session.prepare(
"SELECT DISTINCT tenant_id, tname " +
"FROM metrics_tags_idx"); // Cassandra 3.10 will allow filtering by tenant_id
getTagNamesWithType = session.prepare(
"SELECT tenant_id, tname, type " +
"FROM metrics_tags_idx");
insertIntoMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric, data_retention, tags) " +
"VALUES (?, ?, ?, ?, ?) " +
"IF NOT EXISTS");
insertIntoMetricsIndexOverwrite = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric, data_retention, tags) " +
"VALUES (?, ?, ?, ?, ?) ");
updateMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, metric) VALUES (?, ?, ?)");
addTagsToMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags + ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
deleteTagsFromMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags - ?" +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
readMetricsIndex = session.prepare(
"SELECT metric, tags, data_retention " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? " +
"ORDER BY metric ASC");
findAllMetricsInData = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data");
findAllMetricsInDataCompressed = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, dpart " +
"FROM data_compressed");
findAllMetricsFromTagsIndex = session.prepare(
"SELECT tenant_id, type, metric " +
"FROM metrics_tags_idx");
insertCompressedData = session.prepare(
"UPDATE data_compressed " +
"USING TTL ? " +
"SET c_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertCompressedDataWithTags = session.prepare(
"UPDATE data_compressed " +
"USING TTL ? " +
"SET c_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertStringData = session.prepare(
"UPDATE data " +
"SET s_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ?");
insertStringDataUsingTTL = session.prepare(
"UPDATE data " +
"USING TTL ? " +
"SET s_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ?");
insertStringDataWithTags = session.prepare(
"UPDATE data " +
"SET s_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
insertStringDataWithTagsUsingTTL = session.prepare(
"UPDATE data " +
"USING TTL ? " +
"SET s_value = ?, tags = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time = ? ");
findCompressedDataByDateRangeExclusive = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
findCompressedDataByDateRangeExclusiveWithLimit = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?" +
" LIMIT ?");
findCompressedDataByDateRangeExclusiveASC = session.prepare(
"SELECT time, c_value, tags FROM data_compressed " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC");
findCompressedDataByDateRangeExclusiveWithLimitASC = session.prepare(
"SELECT time, c_value, tags FROM data_compressed" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?");
findStringDataByDateRangeExclusive = session.prepare(
"SELECT time, s_value, tags FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
findStringDataByDateRangeExclusiveWithLimit = session.prepare(
"SELECT time, s_value, tags FROM data " +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?" +
" LIMIT ?");
findStringDataByDateRangeExclusiveASC = session.prepare(
"SELECT time, s_value, tags FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC");
findStringDataByDateRangeExclusiveWithLimitASC = session.prepare(
"SELECT time, s_value, tags FROM data" +
" WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ?" +
" AND time < ? ORDER BY time ASC" +
" LIMIT ?");
deleteMetricData = session.prepare(
"DELETE FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ?");
deleteMetricDataWithLimit = session.prepare(
"DELETE FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = ? AND time >= ? AND time < ?");
deleteFromMetricRetentionIndex = session.prepare(
"DELETE FROM retentions_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
deleteMetricFromMetricsIndex = session.prepare(
"DELETE FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
updateRetentionsIndex = session.prepare(
"INSERT INTO retentions_idx (tenant_id, type, metric, retention) VALUES (?, ?, ?, ?)");
findDataRetentions = session.prepare(
"SELECT tenant_id, type, metric, retention " +
"FROM retentions_idx " +
"WHERE tenant_id = ? AND type = ?");
insertMetricsTagsIndex = session.prepare(
"INSERT INTO metrics_tags_idx (tenant_id, tname, tvalue, type, metric) VALUES (?, ?, ?, ?, ?)");
deleteMetricsTagsIndex = session.prepare(
"DELETE FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ? AND type = ? AND metric = ?");
findMetricsByTagName = session.prepare(
"SELECT tenant_id, type, metric, tvalue " +
"FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ?");
findMetricsByTagNameValue = session.prepare(
"SELECT tenant_id, type, metric, tvalue " +
"FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ?");
updateMetricExpirationIndex = session.prepare(
"INSERT INTO metrics_expiration_idx (tenant_id, type, metric, time) VALUES (?, ?, ?, ?)");
deleteFromMetricExpirationIndex = session.prepare(
"DELETE FROM metrics_expiration_idx " +
"WHERE tenant_id = ? AND type = ? AND metric = ?");
findMetricExpiration = session.prepare(
"SELECT time " +
"FROM metrics_expiration_idx " +
"WHERE tenant_id = ? AND type = ? and metric = ?");
}
@Override
public Observable<ResultSet> insertTenant(Tenant tenant, boolean overwrite) {
Map<String, Integer> retentions = tenant.getRetentionSettings().entrySet().stream()
.collect(toMap(entry -> entry.getKey().getText(), Map.Entry::getValue));
if (overwrite) {
return rxSession.execute(insertTenantOverwrite.bind(tenant.getId(), retentions));
}
return rxSession.execute(insertTenant.bind(tenant.getId(), retentions));
}
@Override
public Observable<Row> findAllTenantIds() {
return rxSession.executeAndFetch(findAllTenantIds.bind())
.concatWith(rxSession.executeAndFetch(findAllTenantIdsFromMetricsIdx.bind()));
}
@Override
public Observable<Row> findTenant(String id) {
return rxSession.executeAndFetch(findTenant.bind(id));
}
@Override
public <T> ResultSetFuture insertMetricInMetricsIndex(Metric<T> metric, boolean overwrite) {
MetricId<T> metricId = metric.getMetricId();
if (overwrite) {
return session.executeAsync(
insertIntoMetricsIndexOverwrite.bind(metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), metric.getDataRetention(), metric.getTags()));
}
return session.executeAsync(insertIntoMetricsIndex.bind(metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), metric.getDataRetention(), metric.getTags()));
}
@Override
public <T> Observable<Row> findMetricInData(MetricId<T> id) {
return getPrepForAllTempTables(TempStatement.CHECK_EXISTENCE_OF_METRIC_IN_TABLE)
.map(b -> b.bind(id.getTenantId(), id.getType().getCode(), id.getName()))
.flatMap(b -> rxSession.executeAndFetch(b))
.concatWith(rxSession.executeAndFetch(findMetricInData
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART))
.concatWith(
rxSession.executeAndFetch(findMetricInDataCompressed
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART))))
.take(1);
}
@Override
public <T> Observable<Row> findMetricInMetricsIndex(MetricId<T> id) {
return rxSession.executeAndFetch(findMetricInMetricsIndex
.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<Row> getMetricTags(MetricId<T> id) {
return rxSession.executeAndFetch(getMetricTags.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public Observable<Row> getTagNames() {
return rxSession.executeAndFetch(getTagNames.bind());
}
@Override
public Observable<Row> getTagNamesWithType() {
return rxSession.executeAndFetch(getTagNamesWithType.bind());
}
@Override
public <T> Observable<ResultSet> addTags(Metric<T> metric, Map<String, String> tags) {
MetricId<T> metricId = metric.getMetricId();
BoundStatement stmt = addTagsToMetricsIndex.bind(tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName());
return rxSession.execute(stmt);
}
@Override
public <T> Observable<ResultSet> deleteTags(Metric<T> metric, Set<String> tags) {
MetricId<T> metricId = metric.getMetricId();
BoundStatement stmt = deleteTagsFromMetricsIndex.bind(tags, metricId.getTenantId(),
metricId.getType().getCode(), metricId.getName());
return rxSession.execute(stmt);
}
@Override
public <T> Observable<Integer> updateMetricsIndex(Observable<Metric<T>> metrics) {
return metrics.map(Metric::getMetricId)
.map(id -> updateMetricsIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()))
.compose(new BatchStatementTransformer())
.flatMap(batch -> rxSession.execute(batch).map(resultSet -> batch.size()));
}
@Override
public <T> Observable<Row> findMetricsInMetricsIndex(String tenantId, MetricType<T> type) {
return rxSession.executeAndFetch(readMetricsIndex.bind(tenantId, type.getCode()));
}
/**
* Fetch all the data from a temporary table for the compression job. Using TokenRanges avoids fetching first
* all the metrics' partition keys and then requesting them.
*
* Performance can be improved by using data locality and fetching with multiple threads.
*
* @param timestamp A timestamp inside the wanted bucket (such as the previous starting row timestamp)
* @param pageSize How many rows to fetch each time
* @param maxConcurrency To how many streams should token ranges be split to
* @return Observable of Observables per partition key
*/
@Override
public Observable<Observable<Row>> findAllDataFromBucket(long timestamp, int pageSize, int maxConcurrency) {
PreparedStatement ts =
getTempStatement(MetricType.UNDEFINED, TempStatement.SCAN_WITH_TOKEN_RANGES, timestamp);
// The table does not exists - case such as when starting Hawkular-Metrics for the first time just before
// compression kicks in.
if(ts == null || prepMap.floorKey(timestamp) == 0L) {
return Observable.empty();
}
return Observable.from(getTokenRanges())
.map(tr -> rxSession.executeAndFetch(
getTempStatement(MetricType.UNDEFINED, TempStatement.SCAN_WITH_TOKEN_RANGES, timestamp)
.bind()
.setToken(0, tr.getStart())
.setToken(1, tr.getEnd())
.setFetchSize(pageSize)));
}
private Set<TokenRange> getTokenRanges() {
Set<TokenRange> tokenRanges = new HashSet<>();
for (TokenRange tokenRange : metadata.getTokenRanges()) {
tokenRanges.addAll(tokenRange.unwrap());
}
return tokenRanges;
}
@Override
public Observable<ResultSet> dropTempTable(long timestamp) {
String fullTableName = getTempTableName(timestamp);
String dropCQL = String.format("DROP TABLE %s", fullTableName);
return rxSession.execute(dropCQL);
}
private Observable<PreparedStatement> getPrepForAllTempTables(TempStatement ts) {
return Observable.from(prepMap.entrySet())
.map(Map.Entry::getValue)
.map(pMap -> pMap.get(getMapKey(MetricType.UNDEFINED, ts)));
}
@Override
public Observable<Row> findAllMetricIdentifiersInData() {
return getPrepForAllTempTables(TempStatement.LIST_ALL_METRICS_FROM_TABLE)
.flatMap(b -> rxSession.executeAndFetch(b.bind()))
.mergeWith(rxSession.executeAndFetch(findAllMetricsInData.bind()))
.mergeWith(rxSession.executeAndFetch(findAllMetricsInDataCompressed.bind()));
}
/*
* Applies micro-batching capabilities by taking advantage of token ranges in the Cassandra
*/
private Observable.Transformer<BoundStatement, Integer> applyMicroBatching() {
return tObservable -> tObservable
.groupBy(b -> {
ByteBuffer routingKey = b.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED,
codecRegistry);
Token token = metadata.newToken(routingKey);
for (TokenRange tokenRange : session.getCluster().getMetadata().getTokenRanges()) {
if (tokenRange.contains(token)) {
return tokenRange;
}
}
log.warn("Unable to find any Cassandra node to insert token " + token.toString());
return session.getCluster().getMetadata().getTokenRanges().iterator().next();
})
.flatMap(g -> g.compose(new BoundBatchStatementTransformer()))
.flatMap(batch -> rxSession
.execute(batch)
.compose(applyInsertRetryPolicy())
.map(resultSet -> batch.size())
);
}
/*
* Apply our current retry policy to the insert behavior
*/
private <T> Observable.Transformer<T, T> applyInsertRetryPolicy() {
return tObservable -> tObservable
.retryWhen(errors -> {
Observable<Integer> range = Observable.range(1, 2);
return errors
.zipWith(range, (t, i) -> {
if (t instanceof DriverException) {
return i;
}
throw Exceptions.propagate(t);
})
.flatMap(retryCount -> {
long delay = (long) Math.min(Math.pow(2, retryCount) * 1000, 3000);
log.debug("Retrying batch insert in " + delay + " ms");
return Observable.timer(delay, TimeUnit.MILLISECONDS);
});
});
}
Long tableToMapKey(String tableName) {
LocalDateTime parsed = LocalDateTime
.parse(tableName.substring(TEMP_TABLE_NAME_PROTOTYPE.length()),
TEMP_TABLE_DATEFORMATTER);
return Long.valueOf(parsed.toInstant(ZoneOffset.UTC).toEpochMilli());
}
String getTempTableName(long timestamp) {
return String.format(TEMP_TABLE_NAME_FORMAT_STRING,
ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), UTC)
.with(DateTimeService.startOfPreviousEvenHour())
.format(TEMP_TABLE_DATEFORMATTER));
}
PreparedStatement getTempStatement(MetricType type, TempStatement ts, long timestamp) {
Map.Entry<Long, Map<Integer, PreparedStatement>> floorEntry = prepMap
.floorEntry(timestamp);
if(floorEntry != null) {
return floorEntry.getValue()
.get(getMapKey(type, ts));
}
return null;
}
@Override
public <T> Observable<Integer> insertData(Observable<Metric<T>> metrics) {
return metrics
.flatMap(m -> Observable.from(m.getDataPoints())
.compose(mapTempInsertStatement(m)))
.compose(applyMicroBatching());
}
@SuppressWarnings("unchecked")
private <T> Observable.Transformer<DataPoint<T>, BoundStatement> mapTempInsertStatement(Metric<T> metric) {
MetricType<T> type = metric.getMetricId().getType();
MetricId<T> metricId = metric.getMetricId();
return tO -> tO
.map(dataPoint -> {
BoundStatement bs;
int i = 1;
PreparedStatement st;
if (dataPoint.getTags().isEmpty()) {
st = getTempStatement(type, TempStatement.INSERT_DATA, dataPoint.getTimestamp());
if(st == null) {
return null;
}
bs = st.bind();
} else {
st = getTempStatement(type, TempStatement.INSERT_DATA_WITH_TAGS, dataPoint.getTimestamp());
if(st == null) {
return null;
}
bs = st.bind();
bs.setMap(1, dataPoint.getTags());
i++;
}
bindValue(bs, type, dataPoint);
return bs
.setString(i, metricId.getTenantId())
.setByte(++i, metricId.getType().getCode())
.setString(++i, metricId.getName())
.setTimestamp(++i, new Date(dataPoint.getTimestamp()));
})
.filter(Objects::nonNull);
}
private <T> void bindValue(BoundStatement bs, MetricType<T> type, DataPoint<T> dataPoint) {
switch(type.getCode()) {
case 0:
bs.setDouble(0, (Double) dataPoint.getValue());
break;
case 1:
bs.setBytes(0, getBytes((DataPoint<AvailabilityType>) dataPoint));
break;
case 2:
bs.setLong(0, (Long) dataPoint.getValue());
break;
case 3:
bs.setLong(0, (Long) dataPoint.getValue());
break;
case 4:
throw new IllegalArgumentException("Not implemented yet");
case 5:
bs.setDouble(0, (Double) dataPoint.getValue());
break;
default:
throw new IllegalArgumentException("Unsupported metricType");
}
}
private Observable.Transformer<DataPoint<String>, BoundStatement> mapStringDatapoint(Metric<String> metric, int
ttl, int maxSize) {
return tObservable -> tObservable
.map(dataPoint -> {
if (maxSize != -1 && dataPoint.getValue().length() > maxSize) {
throw new IllegalArgumentException(dataPoint + " exceeds max string length of " + maxSize +
" characters");
}
if (dataPoint.getTags().isEmpty()) {
if (ttl >= 0) {
return bindDataPoint(insertStringDataUsingTTL, metric, dataPoint.getValue(),
dataPoint.getTimestamp(), ttl);
} else {
return bindDataPoint(insertStringData, metric, dataPoint.getValue(),
dataPoint.getTimestamp());
}
} else {
if (ttl >= 0) {
return bindDataPoint(insertStringDataWithTagsUsingTTL, metric, dataPoint.getValue(),
dataPoint.getTags(), dataPoint.getTimestamp(), ttl);
} else {
return bindDataPoint(insertStringDataWithTags, metric, dataPoint.getValue(),
dataPoint.getTags(), dataPoint.getTimestamp());
}
}
});
}
@Override
public Observable<Integer> insertStringDatas(Observable<Metric<String>> strings,
Function<MetricId<String>, Integer> ttlFetcher, int maxSize) {
return strings
.flatMap(string -> {
int ttl = ttlFetcher.apply(string.getMetricId());
return Observable.from(string.getDataPoints())
.compose(mapStringDatapoint(string, ttl, maxSize));
}
)
.compose(applyMicroBatching());
}
@Override
public Observable<Integer> insertStringData(Metric<String> metric, int maxSize) {
return insertStringData(metric, -1, maxSize);
}
@Override
public Observable<Integer> insertStringData(Metric<String> metric, int ttl, int maxSize) {
return Observable.from(metric.getDataPoints())
.compose(mapStringDatapoint(metric, ttl, maxSize))
.compose(new BatchStatementTransformer())
.flatMap(batch -> rxSession.execute(batch).map(resultSet -> batch.size()));
}
// TODO These are only used by the String methods
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value, long timestamp) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(value, metricId.getTenantId(), metricId.getType().getCode(), metricId.getName(),
DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value, long timestamp,
int ttl) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(ttl, value, metricId.getTenantId(), metricId.getType().getCode(), metricId.getName(),
DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value,
Map<String, String> tags, long timestamp) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(value, tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), DPART, getTimeUUID(timestamp));
}
private BoundStatement bindDataPoint(PreparedStatement statement, Metric<?> metric, Object value,
Map<String, String> tags, long timestamp, int ttl) {
MetricId<?> metricId = metric.getMetricId();
return statement.bind(ttl, value, tags, metricId.getTenantId(), metricId.getType().getCode(),
metricId.getName(), DPART, getTimeUUID(timestamp));
}
@Override
public Observable<Row> findCompressedData(MetricId<?> id, long startTime, long endTime, int limit, Order
order) {
if (order == Order.ASC) {
if (limit <= 0) {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveASC.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime)));
} else {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveWithLimitASC.bind(
id.getTenantId(), id.getType().getCode(), id.getName(), DPART, new Date(startTime),
new Date(endTime), limit));
}
} else {
if (limit <= 0) {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusive.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime)));
} else {
return rxSession.executeAndFetch(findCompressedDataByDateRangeExclusiveWithLimit.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), DPART, new Date(startTime), new Date(endTime),
limit));
}
}
}
private SortedMap<Long, Map<Integer, PreparedStatement>> subSetMap(long startTime, long endTime, Order order) {
Long startKey = prepMap.floorKey(startTime);
Long endKey = prepMap.floorKey(endTime);
// The start time is already compressed, start the request from earliest non-compressed
if(startKey == null) {
startKey = prepMap.ceilingKey(startTime);
}
// Just in case even the end is in the past
if(endKey == null) {
endKey = startKey;
}
// Depending on the order, these must be read in the correct order also..
SortedMap<Long, Map<Integer, PreparedStatement>> statementMap;
if(order == Order.ASC) {
statementMap = prepMap.subMap(startKey, true, endKey,
true);
} else {
statementMap = new ConcurrentSkipListMap<>((var0, var2) -> var0 < var2?1:(var0 == var2?0:-1));
statementMap.putAll(prepMap.subMap(startKey, true, endKey, true));
}
return statementMap;
}
@Override
public <T> Observable<Row> findTempData(MetricId<T> id, long startTime, long endTime, int limit, Order order,
int pageSize) {
MetricType<T> type = id.getType();
SortedMap<Long, Map<Integer, PreparedStatement>> statementMap = subSetMap(startTime, endTime, order);
Observable<Map<Integer, PreparedStatement>> buckets = Observable.from(statementMap.values());
if (order == Order.ASC) {
if (limit <= 0) {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dataByDateRangeExclusiveASC)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(),
new Date(startTime), new Date(endTime))
.setFetchSize(pageSize)));
} else {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dataByDateRangeExclusiveWithLimitASC)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime),
new Date(endTime), limit)
.setFetchSize(pageSize)));
}
} else {
if (limit <= 0) {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dateRangeExclusive)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime),
new Date(endTime))
.setFetchSize(pageSize)));
} else {
return buckets
.map(m -> m.get(getMapKey(type, TempStatement.dateRangeExclusiveWithLimit)))
.concatMap(p -> rxSession.executeAndFetch(p
.bind(id.getTenantId(), id.getType().getCode(), id.getName(), new Date(startTime), new Date(endTime),
limit)
.setFetchSize(pageSize)));
}
}
}
@Override
public Observable<Row> findStringData(MetricId<String> id, long startTime, long endTime, int limit, Order order,
int pageSize) {
if (order == Order.ASC) {
if (limit <= 0) {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveASC.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime))
.setFetchSize(pageSize));
} else {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveWithLimitASC.bind(
id.getTenantId(), STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime),
getTimeUUID(endTime), limit).setFetchSize(pageSize));
}
} else {
if (limit <= 0) {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusive.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime))
.setFetchSize(pageSize));
} else {
return rxSession.executeAndFetch(findStringDataByDateRangeExclusiveWithLimit.bind(id.getTenantId(),
STRING.getCode(), id.getName(), DPART, getTimeUUID(startTime), getTimeUUID(endTime),
limit).setFetchSize(pageSize));
}
}
}
@Override
public <T> Observable<ResultSet> deleteMetricData(MetricId<T> id) {
if(id.getType() == STRING) {
return rxSession.execute(deleteMetricData.bind(id.getTenantId(), id.getType().getCode(), id.getName(), DPART));
}
return getPrepForAllTempTables(TempStatement.DELETE_DATA)
.flatMap(p -> rxSession.execute(p.bind(id.getTenantId(), id.getType().getCode(), id.getName())));
}
@Override
public <T> Observable<ResultSet> deleteMetricFromRetentionIndex(MetricId<T> id) {
return rxSession
.execute(deleteFromMetricRetentionIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<ResultSet> deleteMetricFromMetricsIndex(MetricId<T> id) {
return rxSession
.execute(deleteMetricFromMetricsIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
private ByteBuffer getBytes(DataPoint<AvailabilityType> dataPoint) {
return ByteBuffer.wrap(new byte[]{dataPoint.getValue().getCode()});
}
@Override
public <T> ResultSetFuture findDataRetentions(String tenantId, MetricType<T> type) {
return session.executeAsync(findDataRetentions.bind(tenantId, type.getCode()));
}
@Override
public <T> Observable<ResultSet> updateRetentionsIndex(String tenantId, MetricType<T> type,
Map<String, Integer> retentions) {
return Observable.from(retentions.entrySet())
.map(entry -> updateRetentionsIndex.bind(tenantId, type.getCode(), entry.getKey(), entry.getValue()))
.compose(new BatchStatementTransformer())
.flatMap(rxSession::execute);
}
@Override
public <T> Observable<ResultSet> insertIntoMetricsTagsIndex(Metric<T> metric, Map<String, String> tags) {
MetricId<T> metricId = metric.getMetricId();
return tagsUpdates(tags, (name, value) -> insertMetricsTagsIndex.bind(metricId.getTenantId(), name, value,
metricId.getType().getCode(), metricId.getName()));
}
@Override
public <T> Observable<ResultSet> deleteFromMetricsTagsIndex(MetricId<T> id, Map<String, String> tags) {
return tagsUpdates(tags, (name, value) -> deleteMetricsTagsIndex.bind(id.getTenantId(), name, value,
id.getType().getCode(), id.getName()));
}
private Observable<ResultSet> tagsUpdates(Map<String, String> tags,
BiFunction<String, String, BoundStatement> bindVars) {
return Observable.from(tags.entrySet())
.map(entry -> bindVars.apply(entry.getKey(), entry.getValue()))
.flatMap(rxSession::execute);
}
@Override
public Observable<Row> findMetricsByTagName(String tenantId, String tag) {
return rxSession.executeAndFetch(findMetricsByTagName.bind(tenantId, tag));
}
@Override
public Observable<Row> findMetricsByTagNameValue(String tenantId, String tag, String tvalue) {
return rxSession.executeAndFetch(findMetricsByTagNameValue.bind(tenantId, tag, tvalue));
}
@Override
public <T> ResultSetFuture updateRetentionsIndex(Metric<T> metric) {
return session.executeAsync(updateRetentionsIndex.bind(metric.getMetricId().getTenantId(),
metric.getMetricId().getType().getCode(), metric.getMetricId().getName(), metric.getDataRetention()));
}
@Override
public <T> Observable<ResultSet> insertCompressedData(MetricId<T> id, long timeslice,
CompressedPointContainer cpc, int ttl) {
// ByteBuffer position must be 0!
Observable.just(cpc.getValueBuffer(), cpc.getTimestampBuffer(), cpc.getTagsBuffer())
.doOnNext(bb -> {
if(bb != null && bb.position() != 0) {
bb.rewind();
}
});
BiConsumer<BoundStatement, Integer> mapper = (b, i) -> {
b.setString(i, id.getTenantId())
.setByte(i+1, id.getType().getCode())
.setString(i+2, id.getName())
.setLong(i+3, DPART)
.setTimestamp(i+4, new Date(timeslice));
};
BoundStatement b;
int i = 0;
if(cpc.getTagsBuffer() != null) {
b = insertCompressedDataWithTags.bind()
.setInt(i, ttl)
.setBytes(i+1, cpc.getValueBuffer())
.setBytes(i+2, cpc.getTagsBuffer());
mapper.accept(b, 3);
} else {
b = insertCompressedData.bind()
.setInt(i, ttl)
.setBytes(i+1, cpc.getValueBuffer());
mapper.accept(b, 2);
}
return rxSession.execute(b);
}
@Override
public <T> Observable<ResultSet> deleteAndInsertCompressedGauge(MetricId<T> id, long timeslice,
CompressedPointContainer cpc,
long sliceStart, long sliceEnd, int ttl) {
return Observable.just(deleteMetricDataWithLimit.bind()
.setString(0, id.getTenantId())
.setByte(1, id.getType().getCode())
.setString(2, id.getName())
.setLong(3, DPART)
.setUUID(4, getTimeUUID(sliceStart))
.setUUID(5, getTimeUUID(sliceEnd)))
.concatMap(st -> rxSession.execute(st))
.concatWith(insertCompressedData(id, timeslice, cpc, ttl));
}
@Override
public Observable<Row> findAllMetricsFromTagsIndex() {
return rxSession.executeAndFetch(findAllMetricsFromTagsIndex.bind());
}
@Override
public <T> Observable<ResultSet> updateMetricExpirationIndex(MetricId<T> id, long expirationTime) {
return rxSession.execute(updateMetricExpirationIndex.bind(id.getTenantId(),
id.getType().getCode(), id.getName(), new Date(expirationTime)));
}
@Override
public <T> Observable<ResultSet> deleteFromMetricExpirationIndex(MetricId<T> id) {
return rxSession
.execute(deleteFromMetricExpirationIndex.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
@Override
public <T> Observable<Row> findMetricExpiration(MetricId<T> id) {
return rxSession
.executeAndFetch(findMetricExpiration.bind(id.getTenantId(), id.getType().getCode(), id.getName()));
}
private class TemporaryTableStatementCreator implements SchemaChangeListener {
private final CoreLogger log = CoreLogging.getCoreLogger(TemporaryTableStatementCreator.class);
@Override
public void onTableAdded(TableMetadata tableMetadata) {
log.debugf("Table added %s", tableMetadata.getName());
if(tableMetadata.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
log.debugf("Registering prepared statements for table %s", tableMetadata.getName());
Observable.fromCallable(() -> {
prepareTempStatements(tableMetadata.getName(), tableToMapKey(tableMetadata.getName()));
return null;
})
.subscribeOn(Schedulers.io())
.subscribe();
}
}
@Override
public void onTableRemoved(TableMetadata tableMetadata) {
if(tableMetadata.getName().startsWith(TEMP_TABLE_NAME_PROTOTYPE)) {
log.debugf("Removing prepared statements for table %s", tableMetadata.getName());
removeTempStatements(tableMetadata.getName());
}
}
// Rest are not interesting to us
@Override public void onKeyspaceAdded(KeyspaceMetadata keyspaceMetadata) {}
@Override public void onKeyspaceRemoved(KeyspaceMetadata keyspaceMetadata) {}
@Override public void onKeyspaceChanged(KeyspaceMetadata keyspaceMetadata, KeyspaceMetadata keyspaceMetadata1) {}
@Override public void onTableChanged(TableMetadata tableMetadata, TableMetadata tableMetadata1) {
}
@Override public void onUserTypeAdded(UserType userType) {}
@Override public void onUserTypeRemoved(UserType userType) {}
@Override public void onUserTypeChanged(UserType userType, UserType userType1) {}
@Override public void onFunctionAdded(FunctionMetadata functionMetadata) {}
@Override public void onFunctionRemoved(FunctionMetadata functionMetadata) {}
@Override public void onFunctionChanged(FunctionMetadata functionMetadata, FunctionMetadata functionMetadata1) {}
@Override public void onAggregateAdded(AggregateMetadata aggregateMetadata) {}
@Override public void onAggregateRemoved(AggregateMetadata aggregateMetadata) {}
@Override public void onAggregateChanged(AggregateMetadata aggregateMetadata, AggregateMetadata aggregateMetadata1) {}
@Override public void onMaterializedViewAdded(MaterializedViewMetadata materializedViewMetadata) {}
@Override public void onMaterializedViewRemoved(MaterializedViewMetadata materializedViewMetadata) {}
@Override public void onMaterializedViewChanged(MaterializedViewMetadata materializedViewMetadata,
MaterializedViewMetadata materializedViewMetadata1) {}
@Override public void onRegister(Cluster cluster) {}
@Override public void onUnregister(Cluster cluster) {}
}
void removeTempStatements(String tableName) {
// Find the integer key and remove from prepMap
Long mapKey = tableToMapKey(tableName);
prepMap.remove(mapKey);
}
@Override public void shutdown() {
session.getCluster().unregister(tableCreator);
tableCreator = null;
}
public void setTempTableCreator(TemporaryTableStatementCreator creator) {
if(tableCreator != null) {
session.getCluster().unregister(tableCreator);
}
tableCreator = creator;
session.getCluster().register(tableCreator);
}
}
| [HWKMETRICS-702] Add IF EXISTS to the drop table
| core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/DataAccessImpl.java | [HWKMETRICS-702] Add IF EXISTS to the drop table | <ide><path>ore/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/DataAccessImpl.java
<ide> @Override
<ide> public Observable<ResultSet> dropTempTable(long timestamp) {
<ide> String fullTableName = getTempTableName(timestamp);
<del> String dropCQL = String.format("DROP TABLE %s", fullTableName);
<add> String dropCQL = String.format("DROP TABLE IF EXISTS %s", fullTableName);
<ide> return rxSession.execute(dropCQL);
<ide> }
<ide> |
|
Java | apache-2.0 | 23b12148ff5edc112fa21ae676341c606e99b1e5 | 0 | bitsofproof/supernode,joansmith/supernode | /*
* Copyright 2012 Tamas Blummer [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bitsofproof.supernode.core;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class P2P
{
private static final Logger log = LoggerFactory.getLogger (P2P.class);
private final static int BUFFSIZE = 8 * 1024;
public interface Message
{
public byte[] toByteArray ();
}
protected abstract class Peer
{
private final InetSocketAddress address;
private SocketChannel channel;
private boolean unsolicited;
private final LinkedBlockingQueue<byte[]> writes = new LinkedBlockingQueue<byte[]> ();
private final LinkedBlockingQueue<byte[]> reads = new LinkedBlockingQueue<byte[]> ();
private final Semaphore notListened = new Semaphore (1);
private ByteBuffer pushBackBuffer = null;
private final byte[] closedMark = new byte[0];
private final InputStream readIn = new InputStream ()
{
private ByteArrayInputStream currentRead = null;
@Override
public synchronized int available () throws IOException
{
int a = 0;
if ( currentRead != null )
{
a = currentRead.available ();
if ( a > 0 )
{
return a;
}
}
byte[] next = reads.peek ();
if ( next != null && next != closedMark )
{
return next.length;
}
return 0;
}
@Override
public synchronized int read (byte[] b, int off, int len) throws IOException
{
int need = len;
if ( need <= 0 )
{
return need;
}
do
{
if ( currentRead != null )
{
int r = currentRead.read (b, off, need);
if ( r > 0 )
{
off += r;
need -= r;
}
}
if ( need == 0 )
{
return len;
}
byte[] buf = null;
try
{
buf = reads.poll (READTIMEOUT, TimeUnit.SECONDS);
if ( buf == null || buf == closedMark )
{
return -1;
}
}
catch ( InterruptedException e )
{
throw new IOException (e);
}
currentRead = new ByteArrayInputStream (buf);
} while ( need > 0 );
return len;
}
@Override
public int read (byte[] b) throws IOException
{
return read (b, 0, b.length);
}
@Override
public int read () throws IOException
{
byte[] b = new byte[1];
return read (b, 0, 1);
}
};
protected Peer (InetSocketAddress address)
{
this.address = address;
}
private void connect ()
{
try
{
channel = SocketChannel.open ();
channel.configureBlocking (false);
channel.connect (address);
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.REGISTER, SelectionKey.OP_CONNECT, this));
selector.wakeup ();
log.trace ("Trying to connect " + address);
}
catch ( IOException e )
{
}
}
@Override
public boolean equals (Object obj)
{
return address.equals (((Peer) obj).address);
}
@Override
public int hashCode ()
{
return address.hashCode ();
}
private void process (ByteBuffer buffer, int len)
{
if ( len > 0 )
{
byte[] b = new byte[len];
System.arraycopy (buffer.array (), 0, b, 0, len);
reads.add (b);
if ( notListened.tryAcquire () )
{
listen ();
}
}
}
private ByteBuffer getBuffer ()
{
if ( pushBackBuffer != null )
{
return pushBackBuffer;
}
byte[] next;
if ( (next = writes.poll ()) != null )
{
return ByteBuffer.wrap (next);
}
return null;
}
private void pushBack (ByteBuffer b)
{
pushBackBuffer = b;
}
public InetSocketAddress getAddress ()
{
return address;
}
protected void disconnect ()
{
disconnect (0, 0, null);
}
protected void disconnect (final long timeout, final long bannedFor, final String reason)
{
if ( !channel.isConnected () && !channel.isConnectionPending () )
{
return;
}
try
{
// note that no other reference to peer is stored here
// it might be garbage collected
// somebody else however might have retained a reference, so reduce size.
writes.clear ();
reads.clear ();
reads.add (closedMark);
channel.close ();
openConnections.decrementAndGet ();
connectSlot.release ();
if ( unsolicited )
{
unsolicitedConnectSlot.release ();
}
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
onDisconnect (timeout, bannedFor, reason);
}
});
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.CANCEL, SelectionKey.OP_ACCEPT, null));
selector.wakeup ();
}
catch ( IOException e )
{
}
}
private void listen ()
{
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
Message m = null;
try
{
m = parse (readIn);
receive (m);
if ( readIn.available () > 0 )
{
peerThreads.execute (this);
}
else
{
notListened.release ();
}
}
catch ( Exception e )
{
log.debug ("Exception in message processing", e);
disconnect ();
}
}
});
}
public void send (Message m)
{
writes.add (m.toByteArray ());
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE | SelectionKey.OP_READ, null));
selector.wakeup ();
}
protected abstract Message parse (InputStream readIn) throws IOException;
protected abstract void receive (Message m);
protected abstract void onConnect ();
protected abstract void onDisconnect (long timeout, long bannedForSeconds, String reason);
protected abstract boolean isHandshakeSuccessful ();
}
protected abstract Peer createPeer (InetSocketAddress address, boolean active);
protected abstract boolean discover ();
protected void addPeer (InetAddress addr, int port)
{
InetSocketAddress address = new InetSocketAddress (addr, port);
if ( !runqueue.contains (address) )
{
runqueue.add (address);
}
}
public int getNumberOfConnections ()
{
return openConnections.get ();
}
private final AtomicInteger openConnections = new AtomicInteger (0);
// peers waiting to be connected
private final LinkedBlockingQueue<InetSocketAddress> runqueue = new LinkedBlockingQueue<InetSocketAddress> ();
// number of connections we try to maintain
private final int desiredConnections;
// we want fast answering nodes
private static final int CONNECTIONTIMEOUT = 5;
// number of seconds to wait until giving up on connections
private static final int READTIMEOUT = 5; // seconds
// keep track of connections we asked for
private final Semaphore connectSlot;
// keep track of connections coming unsolicited
private final Semaphore unsolicitedConnectSlot;
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool (1);
private int port;
public void setPort (int port)
{
this.port = port;
}
public int getPort ()
{
return port;
}
protected ScheduledExecutorService getScheduler ()
{
return scheduler;
}
private static class ChangeRequest
{
public static final int REGISTER = 1;
public static final int CHANGEOPS = 2;
public static final int STOP = 3;
public static final int CANCEL = 4;
public SelectableChannel socket;
public int type;
public int ops;
public Peer peer;
public ChangeRequest (SelectableChannel socket, int type, int ops, Peer peer)
{
this.socket = socket;
this.type = type;
this.ops = ops;
this.peer = peer;
}
}
private final ConcurrentLinkedQueue<ChangeRequest> selectorChanges = new ConcurrentLinkedQueue<ChangeRequest> ();
private final Selector selector;
private final ThreadPoolExecutor peerThreads;
private final Thread selectorThread;
private final Thread connector;
private static class PeerFactory implements ThreadFactory
{
final static AtomicInteger peerNumber = new AtomicInteger (0);
@Override
public Thread newThread (final Runnable r)
{
Thread peerThread = new Thread ()
{
@Override
public void run ()
{
r.run ();
}
};
peerThread.setDaemon (false);
peerThread.setName ("Peer-thread-" + peerNumber.getAndIncrement ());
return peerThread;
}
}
public P2P (int connections) throws IOException
{
desiredConnections = connections;
connectSlot = new Semaphore (desiredConnections);
unsolicitedConnectSlot = new Semaphore (desiredConnections / 2);
// create a pool of threads
peerThreads =
(ThreadPoolExecutor) Executors.newFixedThreadPool (Math.min (desiredConnections, Runtime.getRuntime ().availableProcessors () * 2),
new PeerFactory ());
selector = Selector.open ();
// this thread waits on the selector above and acts on events
selectorThread = new Thread (new Runnable ()
{
@Override
public void run ()
{
try
{
ByteBuffer readBuffer = ByteBuffer.allocate (BUFFSIZE);
while ( true )
{
ChangeRequest cr;
while ( (cr = selectorChanges.poll ()) != null )
{
if ( cr.type == ChangeRequest.STOP )
{
return;
}
if ( cr.socket == null )
{
continue;
}
if ( cr.type == ChangeRequest.REGISTER )
{
try
{
SelectionKey key = cr.socket.register (selector, cr.ops);
key.attach (cr.peer);
}
catch ( ClosedChannelException e )
{
continue;
}
}
else if ( cr.type == ChangeRequest.CHANGEOPS )
{
SelectionKey key = cr.socket.keyFor (selector);
if ( key != null )
{
key.interestOps (cr.ops);
}
}
else if ( cr.type == ChangeRequest.CANCEL )
{
SelectionKey key = cr.socket.keyFor (selector);
if ( key != null )
{
key.cancel ();
}
}
}
selector.select ();
Iterator<SelectionKey> keys = selector.selectedKeys ().iterator ();
while ( keys.hasNext () )
{
SelectionKey key = keys.next ();
keys.remove ();
try
{
if ( !key.isValid () )
{
key.attach (null);
continue;
}
if ( key.isAcceptable () )
{
SocketChannel client;
try
{
if ( unsolicitedConnectSlot.tryAcquire () )
{
client = ((ServerSocketChannel) key.channel ()).accept ();
client.configureBlocking (false);
InetSocketAddress address = (InetSocketAddress) client.socket ().getRemoteSocketAddress ();
log.trace ("Unsolicited connection from " + address.getAddress ());
if ( client.isOpen () )
{
final Peer peer;
peer = createPeer (address, false);
peer.channel = client;
peer.unsolicited = true;
client.register (selector, SelectionKey.OP_READ);
key.attach (peer);
openConnections.incrementAndGet ();
scheduler.schedule (new Runnable ()
{
@Override
public void run ()
{
if ( !peer.isHandshakeSuccessful () )
{
peer.disconnect ();
}
}
}, CONNECTIONTIMEOUT, TimeUnit.SECONDS);
}
}
else
{
key.channel ().close ();
key.cancel ();
}
}
catch ( IOException e )
{
log.trace ("unsuccessful unsolicited connection ", e);
}
}
else
{
final Peer peer = (Peer) key.attachment ();
if ( key.isConnectable () )
{
// we asked for connection here
try
{
SocketChannel client = (SocketChannel) key.channel ();
client.finishConnect ();
openConnections.incrementAndGet ();
key.interestOps (SelectionKey.OP_READ);
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
peer.onConnect ();
}
});
}
catch ( IOException e )
{
connectSlot.release ();
key.cancel ();
key.attach (null);
}
}
else
{
try
{
if ( key.isReadable () )
{
SocketChannel client = (SocketChannel) key.channel ();
int len;
len = client.read (readBuffer);
if ( len > 0 )
{
peer.process (readBuffer, len);
readBuffer.clear ();
}
else
{
peer.disconnect ();
}
}
if ( key.isWritable () )
{
SocketChannel client = (SocketChannel) key.channel ();
ByteBuffer b;
if ( (b = peer.getBuffer ()) != null )
{
client.write (b);
int rest = b.remaining ();
if ( rest != 0 )
{
peer.pushBack (b);
}
else
{
peer.pushBack (null);
}
}
else
{
key.interestOps (SelectionKey.OP_READ);
}
}
}
catch ( IOException e )
{
peer.disconnect ();
}
}
}
}
catch ( CancelledKeyException e )
{
final Peer peer = (Peer) key.attachment ();
if ( peer != null )
{
peer.disconnect ();
}
}
}
}
}
catch ( Exception e )
{
log.error ("Fatal selector failure ", e);
}
}
});
selectorThread.setDaemon (false);
selectorThread.setPriority (Thread.NORM_PRIORITY - 1);
selectorThread.setName ("Peer selector");
// this thread keeps looking for new connections
connector = new Thread (new Runnable ()
{
@Override
public void run ()
{
while ( true )
{ // forever
try
{
InetSocketAddress address = runqueue.poll ();
if ( address != null )
{
connectSlot.acquireUninterruptibly ();
final Peer peer = createPeer (address, true);
peer.unsolicited = false;
peer.connect ();
scheduler.schedule (new Runnable ()
{
@Override
public void run ()
{
if ( peer.channel.isConnectionPending () )
{
log.trace ("Give up connect on " + peer.channel);
peer.disconnect (Integer.MAX_VALUE, 0, null);
}
}
}, CONNECTIONTIMEOUT, TimeUnit.SECONDS);
}
else
{
if ( openConnections.get () < desiredConnections )
{
log.trace ("Need to discover new adresses.");
discover ();
if ( runqueue.size () == 0 )
{
log.trace ("Can not find new adresses");
Thread.sleep (60 * 1000);
}
}
else
{
log.trace ("No peer in run queue, but " + openConnections.get () + " connected.");
Thread.sleep (60 * 1000);
}
}
}
catch ( Exception e )
{
log.debug ("Unhandled exception in peer queue", e);
}
}
}
});
connector.setDaemon (true);
connector.setName ("Peer connector");
}
public void stop ()
{
peerThreads.shutdown ();
selectorChanges.add (new ChangeRequest (null, ChangeRequest.STOP, SelectionKey.OP_ACCEPT, null));
selector.wakeup ();
}
public void start () throws IOException
{
final ServerSocketChannel serverChannel = ServerSocketChannel.open ();
serverChannel.socket ().bind (new InetSocketAddress (port));
serverChannel.configureBlocking (false);
selectorChanges.add (new ChangeRequest (serverChannel, ChangeRequest.REGISTER, SelectionKey.OP_ACCEPT, null));
selectorThread.start ();
connector.start ();
}
}
| src/main/java/com/bitsofproof/supernode/core/P2P.java | /*
* Copyright 2012 Tamas Blummer [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bitsofproof.supernode.core;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class P2P
{
private static final Logger log = LoggerFactory.getLogger (P2P.class);
private final static int BUFFSIZE = 8 * 1024;
public interface Message
{
public byte[] toByteArray ();
}
protected abstract class Peer
{
private final InetSocketAddress address;
private SocketChannel channel;
private boolean unsolicited;
private final LinkedBlockingQueue<byte[]> writes = new LinkedBlockingQueue<byte[]> ();
private final LinkedBlockingQueue<byte[]> reads = new LinkedBlockingQueue<byte[]> ();
private final Semaphore notListened = new Semaphore (1);
private ByteBuffer pushBackBuffer = null;
private final byte[] closedMark = new byte[0];
private final InputStream readIn = new InputStream ()
{
private ByteArrayInputStream currentRead = null;
@Override
public synchronized int available () throws IOException
{
int a = 0;
if ( currentRead != null )
{
a = currentRead.available ();
if ( a > 0 )
{
return a;
}
}
byte[] next = reads.peek ();
if ( next != null && next != closedMark )
{
return next.length;
}
return 0;
}
@Override
public synchronized int read (byte[] b, int off, int len) throws IOException
{
int need = len;
if ( need <= 0 )
{
return need;
}
do
{
if ( currentRead != null )
{
int r = currentRead.read (b, off, need);
if ( r > 0 )
{
off += r;
need -= r;
}
}
if ( need == 0 )
{
return len;
}
byte[] buf = null;
try
{
buf = reads.poll (READTIMEOUT, TimeUnit.SECONDS);
if ( buf == null || buf == closedMark )
{
return -1;
}
}
catch ( InterruptedException e )
{
throw new IOException (e);
}
currentRead = new ByteArrayInputStream (buf);
} while ( need > 0 );
return len;
}
@Override
public int read (byte[] b) throws IOException
{
return read (b, 0, b.length);
}
@Override
public int read () throws IOException
{
byte[] b = new byte[1];
return read (b, 0, 1);
}
};
protected Peer (InetSocketAddress address)
{
this.address = address;
}
private void connect ()
{
try
{
channel = SocketChannel.open ();
channel.configureBlocking (false);
channel.connect (address);
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.REGISTER, SelectionKey.OP_CONNECT, this));
selector.wakeup ();
log.trace ("Trying to connect " + address);
}
catch ( IOException e )
{
}
}
@Override
public boolean equals (Object obj)
{
return address.equals (((Peer) obj).address);
}
@Override
public int hashCode ()
{
return address.hashCode ();
}
private void process (ByteBuffer buffer, int len)
{
if ( len > 0 )
{
byte[] b = new byte[len];
System.arraycopy (buffer.array (), 0, b, 0, len);
reads.add (b);
if ( notListened.tryAcquire () )
{
listen ();
}
}
}
private ByteBuffer getBuffer ()
{
if ( pushBackBuffer != null )
{
return pushBackBuffer;
}
byte[] next;
if ( (next = writes.poll ()) != null )
{
return ByteBuffer.wrap (next);
}
return null;
}
private void pushBack (ByteBuffer b)
{
pushBackBuffer = b;
}
public InetSocketAddress getAddress ()
{
return address;
}
protected void disconnect ()
{
disconnect (0, 0, null);
}
protected void disconnect (final long timeout, final long bannedFor, final String reason)
{
if ( !channel.isConnected () && !channel.isConnectionPending () )
{
return;
}
try
{
// note that no other reference to peer is stored here
// it might be garbage collected
// somebody else however might have retained a reference, so reduce size.
writes.clear ();
reads.clear ();
reads.add (closedMark);
channel.close ();
openConnections.decrementAndGet ();
connectSlot.release ();
if ( unsolicited )
{
unsolicitedConnectSlot.release ();
}
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
onDisconnect (timeout, bannedFor, reason);
}
});
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.CANCEL, SelectionKey.OP_ACCEPT, null));
selector.wakeup ();
}
catch ( IOException e )
{
}
}
private void listen ()
{
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
Message m = null;
try
{
m = parse (readIn);
receive (m);
if ( readIn.available () > 0 )
{
peerThreads.execute (this);
}
else
{
notListened.release ();
}
}
catch ( Exception e )
{
log.debug ("Exception in message processing", e);
disconnect ();
}
}
});
}
public void send (Message m)
{
writes.add (m.toByteArray ());
selectorChanges.add (new ChangeRequest (channel, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE | SelectionKey.OP_READ, null));
selector.wakeup ();
}
protected abstract Message parse (InputStream readIn) throws IOException;
protected abstract void receive (Message m);
protected abstract void onConnect ();
protected abstract void onDisconnect (long timeout, long bannedForSeconds, String reason);
protected abstract boolean isHandshakeSuccessful ();
}
protected abstract Peer createPeer (InetSocketAddress address, boolean active);
protected abstract boolean discover ();
protected void addPeer (InetAddress addr, int port)
{
InetSocketAddress address = new InetSocketAddress (addr, port);
if ( !runqueue.contains (address) )
{
runqueue.add (address);
}
}
public int getNumberOfConnections ()
{
return openConnections.get ();
}
private final AtomicInteger openConnections = new AtomicInteger (0);
// peers waiting to be connected
private final LinkedBlockingQueue<InetSocketAddress> runqueue = new LinkedBlockingQueue<InetSocketAddress> ();
// number of connections we try to maintain
private final int desiredConnections;
// we want fast answering nodes
private static final int CONNECTIONTIMEOUT = 5;
// number of seconds to wait until giving up on connections
private static final int READTIMEOUT = 5; // seconds
// keep track of connections we asked for
private final Semaphore connectSlot;
// keep track of connections coming unsolicited
private final Semaphore unsolicitedConnectSlot;
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool (1);
private int port;
public void setPort (int port)
{
this.port = port;
}
public int getPort ()
{
return port;
}
protected ScheduledExecutorService getScheduler ()
{
return scheduler;
}
private static class ChangeRequest
{
public static final int REGISTER = 1;
public static final int CHANGEOPS = 2;
public static final int STOP = 3;
public static final int CANCEL = 4;
public SelectableChannel socket;
public int type;
public int ops;
public Peer peer;
public ChangeRequest (SelectableChannel socket, int type, int ops, Peer peer)
{
this.socket = socket;
this.type = type;
this.ops = ops;
this.peer = peer;
}
}
private final ConcurrentLinkedQueue<ChangeRequest> selectorChanges = new ConcurrentLinkedQueue<ChangeRequest> ();
private final Selector selector;
private final ThreadPoolExecutor peerThreads;
private final Thread selectorThread;
private final Thread connector;
private static class PeerFactory implements ThreadFactory
{
final static AtomicInteger peerNumber = new AtomicInteger (0);
@Override
public Thread newThread (final Runnable r)
{
Thread peerThread = new Thread ()
{
@Override
public void run ()
{
r.run ();
}
};
peerThread.setDaemon (false);
peerThread.setName ("Peer-thread-" + peerNumber.getAndIncrement ());
return peerThread;
}
}
public P2P (int connections) throws IOException
{
desiredConnections = connections;
connectSlot = new Semaphore (desiredConnections);
unsolicitedConnectSlot = new Semaphore (desiredConnections / 2);
// create a pool of threads
peerThreads =
(ThreadPoolExecutor) Executors.newFixedThreadPool (Math.min (desiredConnections, Runtime.getRuntime ().availableProcessors () * 2),
new PeerFactory ());
selector = Selector.open ();
// this thread waits on the selector above and acts on events
selectorThread = new Thread (new Runnable ()
{
@Override
public void run ()
{
try
{
ByteBuffer readBuffer = ByteBuffer.allocate (BUFFSIZE);
while ( true )
{
ChangeRequest cr;
while ( (cr = selectorChanges.poll ()) != null )
{
if ( cr.type == ChangeRequest.STOP )
{
return;
}
if ( cr.socket == null )
{
continue;
}
if ( cr.type == ChangeRequest.REGISTER )
{
try
{
SelectionKey key = cr.socket.register (selector, cr.ops);
key.attach (cr.peer);
}
catch ( ClosedChannelException e )
{
continue;
}
}
else if ( cr.type == ChangeRequest.CHANGEOPS )
{
SelectionKey key = cr.socket.keyFor (selector);
if ( key != null )
{
key.interestOps (cr.ops);
}
}
else if ( cr.type == ChangeRequest.CANCEL )
{
SelectionKey key = cr.socket.keyFor (selector);
if ( key != null )
{
key.cancel ();
}
}
}
selector.select ();
Iterator<SelectionKey> keys = selector.selectedKeys ().iterator ();
while ( keys.hasNext () )
{
SelectionKey key = keys.next ();
keys.remove ();
try
{
if ( !key.isValid () )
{
key.attach (null);
continue;
}
if ( key.isAcceptable () )
{
SocketChannel client;
try
{
if ( unsolicitedConnectSlot.tryAcquire () )
{
client = ((ServerSocketChannel) key.channel ()).accept ();
client.configureBlocking (false);
InetSocketAddress address = (InetSocketAddress) client.socket ().getRemoteSocketAddress ();
log.trace ("Unsolicited connection from " + address.getAddress ());
if ( client.isOpen () )
{
final Peer peer;
peer = createPeer (address, false);
peer.channel = client;
peer.unsolicited = true;
client.register (selector, SelectionKey.OP_READ);
key.attach (peer);
openConnections.incrementAndGet ();
scheduler.schedule (new Runnable ()
{
@Override
public void run ()
{
if ( !peer.isHandshakeSuccessful () )
{
peer.disconnect ();
}
}
}, CONNECTIONTIMEOUT, TimeUnit.SECONDS);
}
}
else
{
key.channel ().close ();
key.cancel ();
}
}
catch ( IOException e )
{
log.trace ("unsuccessful unsolicited connection ", e);
}
}
else
{
final Peer peer = (Peer) key.attachment ();
if ( key.isConnectable () )
{
// we asked for connection here
try
{
SocketChannel client = (SocketChannel) key.channel ();
client.finishConnect ();
openConnections.incrementAndGet ();
key.interestOps (SelectionKey.OP_READ);
peerThreads.execute (new Runnable ()
{
@Override
public void run ()
{
peer.onConnect ();
}
});
}
catch ( IOException e )
{
connectSlot.release ();
key.cancel ();
key.attach (null);
}
}
else
{
try
{
if ( key.isReadable () )
{
SocketChannel client = (SocketChannel) key.channel ();
int len;
len = client.read (readBuffer);
if ( len > 0 )
{
peer.process (readBuffer, len);
readBuffer.clear ();
}
else
{
peer.disconnect ();
}
}
if ( key.isWritable () )
{
SocketChannel client = (SocketChannel) key.channel ();
ByteBuffer b;
if ( (b = peer.getBuffer ()) != null )
{
client.write (b);
int rest = b.remaining ();
if ( rest != 0 )
{
peer.pushBack (b);
}
else
{
peer.pushBack (null);
}
}
else
{
key.interestOps (SelectionKey.OP_READ);
}
}
}
catch ( IOException e )
{
peer.disconnect ();
}
}
}
}
catch ( CancelledKeyException e )
{
final Peer peer = (Peer) key.attachment ();
if ( peer != null )
{
peer.disconnect ();
}
}
}
}
}
catch ( Exception e )
{
log.error ("Fatal selector failure ", e);
}
}
});
selectorThread.setDaemon (false);
selectorThread.setPriority (Thread.NORM_PRIORITY - 1);
selectorThread.setName ("Peer selector");
// this thread keeps looking for new connections
connector = new Thread (new Runnable ()
{
@Override
public void run ()
{
while ( true )
{ // forever
try
{
InetSocketAddress address = runqueue.poll ();
if ( address != null )
{
connectSlot.acquireUninterruptibly ();
final Peer peer = createPeer (address, true);
peer.unsolicited = true;
peer.connect ();
scheduler.schedule (new Runnable ()
{
@Override
public void run ()
{
if ( peer.channel.isConnectionPending () )
{
log.trace ("Give up connect on " + peer.channel);
peer.disconnect (Integer.MAX_VALUE, 0, null);
}
}
}, CONNECTIONTIMEOUT, TimeUnit.SECONDS);
}
else
{
if ( openConnections.get () < desiredConnections )
{
log.trace ("Need to discover new adresses.");
discover ();
if ( runqueue.size () == 0 )
{
log.trace ("Can not find new adresses");
Thread.sleep (60 * 1000);
}
}
else
{
log.trace ("No peer in run queue, but " + openConnections.get () + " connected.");
Thread.sleep (60 * 1000);
}
}
}
catch ( Exception e )
{
log.debug ("Unhandled exception in peer queue", e);
}
}
}
});
connector.setDaemon (true);
connector.setName ("Peer connector");
}
public void stop ()
{
peerThreads.shutdown ();
selectorChanges.add (new ChangeRequest (null, ChangeRequest.STOP, SelectionKey.OP_ACCEPT, null));
selector.wakeup ();
}
public void start () throws IOException
{
final ServerSocketChannel serverChannel = ServerSocketChannel.open ();
serverChannel.socket ().bind (new InetSocketAddress (port));
serverChannel.configureBlocking (false);
selectorChanges.add (new ChangeRequest (serverChannel, ChangeRequest.REGISTER, SelectionKey.OP_ACCEPT, null));
selectorThread.start ();
connector.start ();
}
}
| unsolicited set incorrectly
| src/main/java/com/bitsofproof/supernode/core/P2P.java | unsolicited set incorrectly | <ide><path>rc/main/java/com/bitsofproof/supernode/core/P2P.java
<ide> connectSlot.acquireUninterruptibly ();
<ide>
<ide> final Peer peer = createPeer (address, true);
<del> peer.unsolicited = true;
<add> peer.unsolicited = false;
<ide> peer.connect ();
<ide> scheduler.schedule (new Runnable ()
<ide> { |
|
JavaScript | apache-2.0 | 1815ee7a9e8ae7737c303303a0c595cb5d92966d | 0 | junbon/binary-static-www2,tfoertsch/binary-static,junbon/binary-static-www2,tfoertsch/binary-static | var LiveChartConfig = function(params) {
params = params || {};
this.renderTo = params['renderTo'] || 'live_chart_div';
this.renderHeight = params['renderHeight'] || 450;
this.shift = typeof params['shift'] !== 'undefined' ? params['shift'] : 1;
this.with_trades = typeof params['with_trades'] !== 'undefined' ? params['with_trades'] : 1;
this.streaming_server = page.settings.get('streaming_server');
this.with_marker = typeof params['with_marker'] !== 'undefined' ? params['with_marker'] : 0;
this.force_tick = typeof params['force_tick'] !== 'undefined' ? params['force_tick'] : 0;
this.indicators = [];
this.resolutions = {
'tick': {seconds: 0, interval: 3600},
'1m': {seconds: 60, interval: 86400},
'5m': {seconds: 300, interval: 7*86400},
'30m': {seconds: 1800, interval: 31*86400},
'1h': {seconds: 3600, interval: 62*86400},
'8h': {seconds: 8*3600, interval: 183*86400},
'1d': {seconds: 86400, interval: 366*3*86400}
};
this.resolution = 'tick';
this.with_markers = typeof params['with_markers'] !== 'undefined' ? params['with_markers'] : false;
var res,
symbol,
hash = window.location.hash;
res = hash.match(/^#([A-Za-z0-9_]+):(10min|1h|1d|1w|1m|3m|1y)$/);
if (res) {
symbol = markets.by_symbol(res[1]);
if (symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
this.live = res[2];
}
} else {
res = hash.match(/^#([A-Za-z0-9_]+):([0-9]+)-([0-9]+)$/);
if (res) {
symbol = markets.by_symbol(res[1]);
if (symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
this.from = parseInt(res[2]);
this.to = parseInt(res[3]);
this.resolution = this.best_resolution(this.from, this.to);
}
} else {
symbol = markets.by_symbol(params['symbol']) || markets.by_symbol(LocalStore.get('live_chart.symbol')) || markets.by_symbol('frxAUDJPY');
this.symbol = symbol.underlying;
this.market = symbol.market;
var from = params['from'] || LocalStore.get('live_chart.from');
var to = params['to'] || LocalStore.get('live_chart.to');
if (from && to && from != 'null' && to != 'null') {
this.from = from;
this.to = to;
this.resolution = this.best_resolution(this.from, this.to);
} else {
this.live = params['live'] || LocalStore.get('live_chart.live') || '10min';
}
}
}
if (this.live) {
this.from = this.calculate_from(this.live);
this.resolution = this.best_resolution(this.from, new Date().getTime()/1000);
}
};
LiveChartConfig.prototype = {
add_indicator: function(indicator) {
this.indicators.push(indicator);
},
remove_indicator: function(name) {
var deleted_indicator;
var indicator = this.indicators.length;
while(indicator--) {
if(this.indicators[indicator].name == name) {
deleted_indicator = this.indicators[indicator];
this.indicators.splice(indicator, 1);
}
}
return deleted_indicator;
},
has_indicator: function(name) {
var indicator = this.indicators.length;
while(indicator--) {
if(this.indicators[indicator].name == name) {
return true;
}
}
return false;
},
repaint_indicators: function(chart) {
var indicator = this.indicators.length;
while(indicator--) {
this.indicators[indicator].repaint(chart);
}
},
calculate_from: function(len) {
var now = new Date();
var epoch = Math.floor(now.getTime() / 1000);
var units = { min: 60, h: 3600, d: 86400, w: 86400 * 7, m: 86400 * 31, y: 86400 * 366 };
var res = len.match(/^([0-9]+)([hdwmy]|min)$/);
return res ? epoch - parseInt(res[1]) * units[res[2]] : undefined;
},
update: function(opts) {
if (opts.interval) {
var from = parseInt(opts.interval.from.getTime() / 1000);
var to = parseInt(opts.interval.to.getTime() / 1000);
var length = to - from;
this.resolution = this.best_resolution(from, to);
delete opts.interval;
this.from = from;
this.to = to;
delete this.live;
}
if (opts.live) {
delete this.to;
LocalStore.remove('live_chart.to');
LocalStore.remove('live_chart.from');
this.from = this.calculate_from(opts.live);
this.live = opts.live;
LocalStore.set('live_chart.live', opts.live);
this.resolution = this.best_resolution(this.from, new Date().getTime()/1000);
}
if (opts.symbol) {
var symbol = markets.by_symbol(opts.symbol);
if(symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
LocalStore.set('live_chart.symbol', symbol.symbol);
}
}
if(opts.update_url) {
var hash = "#";
if (this.from && this.to) {
hash += this.symbol.symbol + ":" + this.from + "-" + this.to;
} else {
hash += this.symbol.symbol + ":" + this.live;
}
var url = window.location.pathname + window.location.search + hash;
page.url.update(url);
}
if(opts.shift) {
this.shift = opts.shift;
}
if(opts.with_trades) {
this.with_trades = opts.with_trades;
}
if(opts.with_markers) {
this.with_markers = opts.with_markers;
}
if(opts.force_tick) {
this.force_tick = opts.force_tick;
}
},
best_resolution: function(from, to) {
if(this.force_tick) {
return 'tick';
}
var length = parseInt(to - from);
for(var resolution in this.resolutions) {
if (this.resolutions[resolution].interval >= length) {
return resolution;
}
}
return '1d';
},
resolution_seconds: function(resolution) {
resolution = typeof resolution !== 'undefined' ? resolution : this.resolution;
return this.resolutions[resolution]['seconds'];
},
};
var configured_livechart = false;
var configure_livechart = function () {
if(!configured_livechart) {
Highcharts.setOptions({
lang: {
loading: text.localize('loading...'),
printChart: text.localize('Print chart'),
downloadJPEG: text.localize('Save as JPEG'),
downloadPNG: text.localize('Save as PNG'),
downloadSVG: text.localize('Save as SVG'),
downloadPDF: text.localize('Save as PDF'),
downloadCSV: text.localize('Save as CSV'),
rangeSelectorFrom: text.localize('From'),
rangeSelectorTo: text.localize('To'),
rangeSelectorZoom: text.localize('Zoom'),
months: [
text.localize('January'), text.localize('February'), text.localize('March'), text.localize('April'), text.localize('May'), text.localize('June'),
text.localize('July'), text.localize('August'), text.localize('September'), text.localize('October'), text.localize('November'), text.localize('December')
],
shortMonths: [
text.localize('Jan'), text.localize('Feb'), text.localize('Mar'), text.localize('Apr'), text.localize('May'), text.localize('Jun'),
text.localize('Jul'), text.localize('Aug'), text.localize('Sep'), text.localize('Oct'), text.localize('Nov'), text.localize('Dec')
],
weekdays: [
text.localize('Sunday'), text.localize('Monday'), text.localize('Tuesday'), text.localize('Wednesday'),
text.localize('Thursday'), text.localize('Friday'), text.localize('Saturday')
],
},
navigator: {
series: {
includeInCSVExport: false
}
}
});
}
configured_livechart = true;
};
| src/javascript/binary/livechart/config.js | var LiveChartConfig = function(params) {
params = params || {};
this.renderTo = params['renderTo'] || 'live_chart_div';
this.renderHeight = params['renderHeight'] || 450;
this.shift = typeof params['shift'] !== 'undefined' ? params['shift'] : 1;
this.with_trades = typeof params['with_trades'] !== 'undefined' ? params['with_trades'] : 1;
this.streaming_server = page.settings.get('streaming_server');
this.with_marker = typeof params['with_marker'] !== 'undefined' ? params['with_marker'] : 0;
this.force_tick = typeof params['force_tick'] !== 'undefined' ? params['force_tick'] : 0;
this.indicators = [];
this.resolutions = {
'tick': {seconds: 0, interval: 3600},
'1m': {seconds: 60, interval: 86400},
'5m': {seconds: 300, interval: 7*86400},
'30m': {seconds: 1800, interval: 31*86400},
'1h': {seconds: 3600, interval: 62*86400},
'8h': {seconds: 8*3600, interval: 183*86400},
'1d': {seconds: 86400, interval: 366*3*86400}
};
this.resolution = 'tick';
this.with_markers = typeof params['with_markers'] !== 'undefined' ? params['with_markers'] : false;
var res,
symbol,
hash = window.location.hash;
res = hash.match(/^#([A-Za-z0-9_]+):(10min|1h|1d|1w|1m|3m|1y)$/);
if (res) {
symbol = markets.by_symbol(res[1]);
if (symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
this.live = res[2];
}
} else {
res = hash.match(/^#([A-Za-z0-9_]+):([0-9]+)-([0-9]+)$/);
if (res) {
symbol = markets.by_symbol(res[1]);
if (symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
this.from = parseInt(res[2]);
this.to = parseInt(res[3]);
this.resolution = this.best_resolution(this.from, this.to);
}
} else {
symbol = markets.by_symbol(params['symbol']) || markets.by_symbol(LocalStore.get('live_chart.symbol')) || markets.by_symbol('R_100');
this.symbol = symbol.underlying;
this.market = symbol.market;
var from = params['from'] || LocalStore.get('live_chart.from');
var to = params['to'] || LocalStore.get('live_chart.to');
if (from && to && from != 'null' && to != 'null') {
this.from = from;
this.to = to;
this.resolution = this.best_resolution(this.from, this.to);
} else {
this.live = params['live'] || LocalStore.get('live_chart.live') || '10min';
}
}
}
if (this.live) {
this.from = this.calculate_from(this.live);
this.resolution = this.best_resolution(this.from, new Date().getTime()/1000);
}
};
LiveChartConfig.prototype = {
add_indicator: function(indicator) {
this.indicators.push(indicator);
},
remove_indicator: function(name) {
var deleted_indicator;
var indicator = this.indicators.length;
while(indicator--) {
if(this.indicators[indicator].name == name) {
deleted_indicator = this.indicators[indicator];
this.indicators.splice(indicator, 1);
}
}
return deleted_indicator;
},
has_indicator: function(name) {
var indicator = this.indicators.length;
while(indicator--) {
if(this.indicators[indicator].name == name) {
return true;
}
}
return false;
},
repaint_indicators: function(chart) {
var indicator = this.indicators.length;
while(indicator--) {
this.indicators[indicator].repaint(chart);
}
},
calculate_from: function(len) {
var now = new Date();
var epoch = Math.floor(now.getTime() / 1000);
var units = { min: 60, h: 3600, d: 86400, w: 86400 * 7, m: 86400 * 31, y: 86400 * 366 };
var res = len.match(/^([0-9]+)([hdwmy]|min)$/);
return res ? epoch - parseInt(res[1]) * units[res[2]] : undefined;
},
update: function(opts) {
if (opts.interval) {
var from = parseInt(opts.interval.from.getTime() / 1000);
var to = parseInt(opts.interval.to.getTime() / 1000);
var length = to - from;
this.resolution = this.best_resolution(from, to);
delete opts.interval;
this.from = from;
this.to = to;
delete this.live;
}
if (opts.live) {
delete this.to;
LocalStore.remove('live_chart.to');
LocalStore.remove('live_chart.from');
this.from = this.calculate_from(opts.live);
this.live = opts.live;
LocalStore.set('live_chart.live', opts.live);
this.resolution = this.best_resolution(this.from, new Date().getTime()/1000);
}
if (opts.symbol) {
var symbol = markets.by_symbol(opts.symbol);
if(symbol) {
this.symbol = symbol.underlying;
this.market = symbol.market;
LocalStore.set('live_chart.symbol', symbol.symbol);
}
}
if(opts.update_url) {
var hash = "#";
if (this.from && this.to) {
hash += this.symbol.symbol + ":" + this.from + "-" + this.to;
} else {
hash += this.symbol.symbol + ":" + this.live;
}
var url = window.location.pathname + window.location.search + hash;
page.url.update(url);
}
if(opts.shift) {
this.shift = opts.shift;
}
if(opts.with_trades) {
this.with_trades = opts.with_trades;
}
if(opts.with_markers) {
this.with_markers = opts.with_markers;
}
if(opts.force_tick) {
this.force_tick = opts.force_tick;
}
},
best_resolution: function(from, to) {
if(this.force_tick) {
return 'tick';
}
var length = parseInt(to - from);
for(var resolution in this.resolutions) {
if (this.resolutions[resolution].interval >= length) {
return resolution;
}
}
return '1d';
},
resolution_seconds: function(resolution) {
resolution = typeof resolution !== 'undefined' ? resolution : this.resolution;
return this.resolutions[resolution]['seconds'];
},
};
var configured_livechart = false;
var configure_livechart = function () {
if(!configured_livechart) {
Highcharts.setOptions({
lang: {
loading: text.localize('loading...'),
printChart: text.localize('Print chart'),
downloadJPEG: text.localize('Save as JPEG'),
downloadPNG: text.localize('Save as PNG'),
downloadSVG: text.localize('Save as SVG'),
downloadPDF: text.localize('Save as PDF'),
downloadCSV: text.localize('Save as CSV'),
rangeSelectorFrom: text.localize('From'),
rangeSelectorTo: text.localize('To'),
rangeSelectorZoom: text.localize('Zoom'),
months: [
text.localize('January'), text.localize('February'), text.localize('March'), text.localize('April'), text.localize('May'), text.localize('June'),
text.localize('July'), text.localize('August'), text.localize('September'), text.localize('October'), text.localize('November'), text.localize('December')
],
shortMonths: [
text.localize('Jan'), text.localize('Feb'), text.localize('Mar'), text.localize('Apr'), text.localize('May'), text.localize('Jun'),
text.localize('Jul'), text.localize('Aug'), text.localize('Sep'), text.localize('Oct'), text.localize('Nov'), text.localize('Dec')
],
weekdays: [
text.localize('Sunday'), text.localize('Monday'), text.localize('Tuesday'), text.localize('Wednesday'),
text.localize('Thursday'), text.localize('Friday'), text.localize('Saturday')
],
},
navigator: {
series: {
includeInCSVExport: false
}
}
});
}
configured_livechart = true;
};
| change default of livechart
| src/javascript/binary/livechart/config.js | change default of livechart | <ide><path>rc/javascript/binary/livechart/config.js
<ide> this.resolution = this.best_resolution(this.from, this.to);
<ide> }
<ide> } else {
<del> symbol = markets.by_symbol(params['symbol']) || markets.by_symbol(LocalStore.get('live_chart.symbol')) || markets.by_symbol('R_100');
<add> symbol = markets.by_symbol(params['symbol']) || markets.by_symbol(LocalStore.get('live_chart.symbol')) || markets.by_symbol('frxAUDJPY');
<ide> this.symbol = symbol.underlying;
<ide> this.market = symbol.market;
<ide> var from = params['from'] || LocalStore.get('live_chart.from'); |
|
Java | apache-2.0 | 61bc8f5bbe1a77b96bbcf8bf4d03c5aff4579c68 | 0 | Plonk42/mytracks | /*
* Copyright 2013 Google 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.google.android.apps.mytracks.io.sync;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.file.exporter.KmzTrackExporter;
import com.google.android.apps.mytracks.io.file.importer.KmlFileTrackImporter;
import com.google.android.apps.mytracks.io.file.importer.KmzTrackImporter;
import com.google.android.apps.mytracks.io.file.importer.TrackImporter;
import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.maps.mytracks.R;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Changes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.About;
import com.google.api.services.drive.model.Change;
import com.google.api.services.drive.model.ChangeList;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* SyncAdapter to sync tracks with Google Drive.
*
* @author Jimmy Shih
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = SyncAdapter.class.getSimpleName();
// drive.about.get fields. Contains one field, largestChangeId
private static final String ABOUT_GET_FIELDS = "largestChangeId";
private final Context context;
private final MyTracksProviderUtils myTracksProviderUtils;
private Drive drive;
private String driveAccountName; // the account name associated with the drive
private String folderId;
public SyncAdapter(Context context) {
super(context, true);
this.context = context;
this.myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
if (!PreferencesUtils.getBoolean(
context, R.string.drive_sync_key, PreferencesUtils.DRIVE_SYNC_DEFAULT)) {
return;
}
if (account == null) {
return;
}
String googleAccount = PreferencesUtils.getString(
context, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT);
if (googleAccount == null || googleAccount.equals(PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT)) {
return;
}
if (!googleAccount.equals(account.name)) {
return;
}
try {
GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(
context, account.name, SendToGoogleUtils.DRIVE_SCOPE);
if (credential == null) {
return;
}
if (drive == null || !driveAccountName.equals(account.name)) {
drive = SyncUtils.getDriveService(credential);
driveAccountName = account.name;
}
folderId = getFolderId();
long largestChangeId = PreferencesUtils.getLong(
context, R.string.drive_largest_change_id_key);
if (largestChangeId == PreferencesUtils.DRIVE_LARGEST_CHANGE_ID_DEFAULT) {
performInitialSync();
} else {
performIncrementalSync(largestChangeId);
}
insertNewDriveFiles();
} catch (UserRecoverableAuthException e) {
SendToGoogleUtils.sendNotification(
context, account.name, e.getIntent(), SendToGoogleUtils.DRIVE_NOTIFICATION_ID);
} catch (GoogleAuthException e) {
Log.e(TAG, "GoogleAuthException", e);
} catch (UserRecoverableAuthIOException e) {
SendToGoogleUtils.sendNotification(
context, account.name, e.getIntent(), SendToGoogleUtils.DRIVE_NOTIFICATION_ID);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
/**
* Gets the folder id..
*/
private String getFolderId() throws IOException {
File folder = SyncUtils.getMyTracksFolder(context, drive);
if (folder == null) {
throw new IOException("folder is null");
}
String id = folder.getId();
if (id == null) {
throw new IOException("folder id is null");
}
return id;
}
/**
* Performs initial sync.
*/
private void performInitialSync() throws IOException {
// Get the largest change id first to avoid race conditions
About about = drive.about().get().setFields(ABOUT_GET_FIELDS).execute();
long largestChangeId = about.getLargestChangeId();
// Get all the KML/KMZ files in the "My Drive:/My Tracks" folder
Files.List myTracksFolderRequest = drive.files()
.list().setQ(String.format(Locale.US, SyncUtils.MY_TRACKS_FOLDER_FILES_QUERY, folderId));
Map<String, File> myTracksFolderMap = getFiles(myTracksFolderRequest, true);
// Handle tracks that are already uploaded to Google Drive
Set<String> syncedDriveIds = updateSyncedTracks();
for (String driveId : syncedDriveIds) {
myTracksFolderMap.remove(driveId);
}
// Get all the KML/KMZ files in the "Shared with me:/" folder
Files.List sharedWithMeRequest = drive.files()
.list().setQ(SyncUtils.SHARED_WITH_ME_FILES_QUERY);
Map<String, File> sharedWithMeMap = getFiles(sharedWithMeRequest, false);
try {
insertNewTracks(myTracksFolderMap.values());
insertNewTracks(sharedWithMeMap.values());
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, largestChangeId);
} catch (IOException e) {
// Remove all imported tracks
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
if (!syncedDriveIds.contains(track.getDriveId())) {
myTracksProviderUtils.deleteTrack(context, track.getId());
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
throw e;
}
}
/**
* Updates synced tracks.
*
* @return drive ids of the synced tracks
*/
private Set<String> updateSyncedTracks() throws IOException {
Set<String> result = new HashSet<String>();
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
String driveId = track.getDriveId();
if (driveId != null && !driveId.equals("")) {
if (!track.isSharedWithMe()) {
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)) {
merge(track, driveFile);
result.add(driveId);
} else {
/*
* Track has a drive id, but the drive id is no longer valid.
* E.g., the file is moved to another folder. Clear the drive
* id.
*/
SyncUtils.updateTrack(myTracksProviderUtils, track, null);
}
}
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* Performs incremental sync.
*
* @param largestChangeId the largest change id
*/
private void performIncrementalSync(long largestChangeId) throws IOException {
// Handle deleted tracks
String driveDeletedList = PreferencesUtils.getString(
context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT);
if (!PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT.equals(driveDeletedList)) {
String deletedIds[] = TextUtils.split(driveDeletedList, ";");
for (String driveId : deletedIds) {
deleteDriveFile(driveId, true);
}
PreferencesUtils.setString(
context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT);
}
// Handle edited tracks
String driveEditedList = PreferencesUtils.getString(
context, R.string.drive_edited_list_key, PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT);
if (!PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT.equals(driveEditedList)) {
String editedIds[] = TextUtils.split(driveEditedList, ";");
for (String id : editedIds) {
Track track = myTracksProviderUtils.getTrack(Long.valueOf(id));
if (track == null) {
continue;
}
if (track.isSharedWithMe()) {
continue;
}
String driveId = track.getDriveId();
if (driveId == null || driveId.equals("")) {
continue;
}
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)) {
merge(track, driveFile);
}
}
PreferencesUtils.setString(
context, R.string.drive_edited_list_key, PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT);
}
// Handle changes from Google Drive
Map<String, File> changes = new HashMap<String, File>();
long newLargestChangeId = getDriveChangesInfo(largestChangeId, changes);
if (newLargestChangeId != largestChangeId) {
Cursor cursor = null;
try {
// Get all the local tracks with drive file id
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
String driveId = track.getDriveId();
if (changes.containsKey(driveId)) {
// Track has changed
File driveFile = changes.get(driveId);
if (driveFile == null) {
Log.d(TAG, "Delete local track " + track.getName());
myTracksProviderUtils.deleteTrack(context, track.getId());
} else {
if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)
|| SyncUtils.isInSharedWithMe(driveFile)) {
merge(track, driveFile);
} else {
SyncUtils.updateTrack(myTracksProviderUtils, track, null);
}
}
changes.remove(driveId);
}
} while (cursor.moveToNext());
}
// Insert valid new drive file changes as new tracks
Iterator<String> iterator = changes.keySet().iterator();
while (iterator.hasNext()) {
String driveId = iterator.next();
File file = changes.get(driveId);
if (!SyncUtils.isInMyTracksAndValid(file, folderId)
&& !SyncUtils.isInSharedWithMeAndValid(file)) {
iterator.remove();
}
}
insertNewTracks(changes.values());
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, newLargestChangeId);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
/**
* Inserts new drive files from tracks without a drive id.
*/
private void insertNewDriveFiles() throws IOException {
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.NO_DRIVE_ID_TRACKS_QUERY, null, null);
long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
if (track.getId() == recordingTrackId) {
continue;
}
// If not successful, the next sync will retry again
SyncUtils.insertDriveFile(drive, folderId, context, myTracksProviderUtils, track, true);
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/**
* Inserts new tracks from a collection of drive files.
*
* @param driveFiles the drive files
*/
private void insertNewTracks(Collection<File> driveFiles) throws IOException {
for (File driveFile : driveFiles) {
if (driveFile == null) {
return;
}
updateTrack(-1L, driveFile);
}
}
/**
* Gets all the files from a request.
*
* @param request the request
* @param excludeSharedWithMe true to exclude shared with me files
* @return a map of file id to file
*/
private Map<String, File> getFiles(Files.List request, boolean excludeSharedWithMe)
throws IOException {
Map<String, File> idToFileMap = new HashMap<String, File>();
do {
FileList files = request.execute();
for (File file : files.getItems()) {
if (excludeSharedWithMe && file.getSharedWithMeDate() != null) {
continue;
}
idToFileMap.put(file.getId(), file);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
return idToFileMap;
}
/**
* Gets the drive changes info in the My Tracks folder, including deleted
* files.
*
* @param changeId the largest change id
* @param changes a map of drive id to file for the changes
* @return an updated largest change id
*/
private long getDriveChangesInfo(long changeId, Map<String, File> changes) throws IOException {
Changes.List request = drive.changes().list().setStartChangeId(changeId + 1);
do {
ChangeList changeList = request.execute();
long newId = changeList.getLargestChangeId().longValue();
for (Change change : changeList.getItems()) {
if (change.getDeleted()) {
changes.put(change.getFileId(), null);
} else {
File file = change.getFile();
if (file.getLabels().getTrashed()) {
changes.put(change.getFileId(), null);
} else {
changes.put(change.getFileId(), file);
}
}
}
if (newId > changeId) {
changeId = newId;
}
request.setPageToken(changeList.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
Log.d(TAG, "Got drive changes: " + changes.size() + " " + changeId);
return changeId;
}
/**
* Merges a track with a drive file.
*
* @param track the track
* @param driveFile the drive file
*/
private void merge(Track track, File driveFile) throws IOException {
long modifiedTime = track.getModifiedTime();
long driveModifiedTime = driveFile.getModifiedDate().getValue();
if (modifiedTime > driveModifiedTime) {
Log.d(TAG, "Updating track change for track " + track.getName() + " and drive file "
+ driveFile.getTitle());
if (!SyncUtils.updateDriveFile(
drive, driveFile, context, myTracksProviderUtils, track, true)) {
Log.e(TAG, "Unable to update drive file");
track.setModifiedTime(driveModifiedTime);
myTracksProviderUtils.updateTrack(track);
}
} else if (modifiedTime < driveModifiedTime) {
Log.d(TAG, "Updating drive change for track " + track.getName() + " and drive file "
+ driveFile.getTitle());
if (!updateTrack(track.getId(), driveFile)) {
Log.e(TAG, "Unable to update drive change");
// The track could have been deleted in the unsuccessful update
track = myTracksProviderUtils.getTrack(track.getId());
if (track != null) {
track.setModifiedTime(driveModifiedTime);
myTracksProviderUtils.updateTrack(track);
}
}
}
}
/**
* Updates a track based on a drive file. Returns true if successful.
*
* @param trackId the track id. -1L to insert a new track
* @param driveFile the drive file
*/
private boolean updateTrack(final long trackId, File driveFile) throws IOException {
Track track = null;
boolean success = false;
try {
track = importDriveFile(trackId, driveFile);
if (track == null) {
return false;
}
File updatedDriveFile;
String trackName = FileUtils.getName(driveFile.getTitle());
if (SyncUtils.isInMyTracks(driveFile, folderId) && !track.getName().equals(trackName)) {
track.setName(trackName);
/*
* The drive file title and the track name inside the drive file do not
* match, update the drive file.
*/
java.io.File file = null;
try {
file = SyncUtils.getTempFile(context, myTracksProviderUtils, track, true);
updatedDriveFile = SyncUtils.updateDriveFile(
drive, driveFile, trackName + "." + KmzTrackExporter.KMZ_EXTENSION, file, true);
if (updatedDriveFile == null) {
Log.e(TAG, "Unable to update drive file");
return false;
}
} finally {
if (file != null) {
file.delete();
}
}
} else {
updatedDriveFile = driveFile;
}
SyncUtils.updateTrack(myTracksProviderUtils, track, updatedDriveFile);
success = true;
return true;
} finally {
if (!success) {
// if the track is new, delete it
if (trackId == -1L && track != null) {
myTracksProviderUtils.deleteTrack(context, track.getId());
}
}
}
}
/**
* Imports drive file to track.
*
* @param trackId the track id. -1L to insert a new track
* @param driveFile the drive file
*/
private Track importDriveFile(long trackId, File driveFile) throws IOException {
InputStream inputStream = null;
try {
inputStream = downloadDriveFile(driveFile, true);
if (inputStream == null) {
Log.e(TAG, "Unable to import drive file. Input stream is null.");
return null;
}
TrackImporter trackImporter;
boolean useKmz = KmzTrackExporter.KMZ_EXTENSION.equals(driveFile.getFileExtension());
if (useKmz) {
if (trackId == -1L) {
Uri uri = myTracksProviderUtils.insertTrack(new Track());
trackId = Long.parseLong(uri.getLastPathSegment());
}
trackImporter = new KmzTrackImporter(context, trackId);
} else {
trackImporter = new KmlFileTrackImporter(context, trackId);
}
long importedId = trackImporter.importFile(inputStream);
if (importedId == -1L) {
Log.e(TAG, "Unable to import drive file. Imported id is -1L.");
return null;
}
Track track = myTracksProviderUtils.getTrack(importedId);
if (track == null) {
Log.e(TAG, "Unable to import drive file. Imported track is null.");
return null;
} else {
return track;
}
} catch (IOException e) {
Log.e(TAG, "Unable to import drive file.", e);
return null;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
/**
* Deletes a drive file.
*
* @param driveId the drive id
* @param canRetry true if can retry the request
* @throws IOException
*/
private void deleteDriveFile(String driveId, boolean canRetry) throws IOException {
try {
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracks(driveFile, folderId)) {
if (!driveFile.getLabels().getTrashed()) {
drive.files().trash(driveId).execute();
}
// if trashed, ignore
} else if (SyncUtils.isInSharedWithMe(driveFile)) {
if (!driveFile.getLabels().getTrashed()) {
drive.files().delete(driveId).execute();
}
// if trashed, ignore
}
} catch (UserRecoverableAuthIOException e) {
throw e;
} catch (IOException e) {
if (canRetry) {
deleteDriveFile(driveId, false);
return;
}
Log.e(TAG, "Unable to delete Drive file for " + driveId, e);
}
}
/**
* Downloads a drive file.
*
* @param driveFile the drive file
*/
private InputStream downloadDriveFile(File driveFile, boolean canRetry) throws IOException {
if (driveFile.getDownloadUrl() == null || driveFile.getDownloadUrl().length() == 0) {
Log.d(TAG, "Drive file download url doesn't exist: " + driveFile.getTitle());
return null;
}
try {
HttpResponse httpResponse = drive.getRequestFactory()
.buildGetRequest(new GenericUrl(driveFile.getDownloadUrl())).execute();
if (httpResponse == null) {
Log.e(TAG, "http response is null");
return null;
}
return httpResponse.getContent();
} catch (UserRecoverableAuthIOException e) {
throw e;
} catch (IOException e) {
if (canRetry) {
return downloadDriveFile(driveFile, false);
}
throw e;
}
}
}
| MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java | /*
* Copyright 2013 Google 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.google.android.apps.mytracks.io.sync;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.file.exporter.KmzTrackExporter;
import com.google.android.apps.mytracks.io.file.importer.KmlFileTrackImporter;
import com.google.android.apps.mytracks.io.file.importer.KmzTrackImporter;
import com.google.android.apps.mytracks.io.file.importer.TrackImporter;
import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.maps.mytracks.R;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Changes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.About;
import com.google.api.services.drive.model.Change;
import com.google.api.services.drive.model.ChangeList;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* SyncAdapter to sync tracks with Google Drive.
*
* @author Jimmy Shih
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = SyncAdapter.class.getSimpleName();
// drive.about.get fields. Contains one field, largestChangeId
private static final String ABOUT_GET_FIELDS = "largestChangeId";
private final Context context;
private final MyTracksProviderUtils myTracksProviderUtils;
private Drive drive;
private String driveAccountName; // the account name associated with the drive
private String folderId;
public SyncAdapter(Context context) {
super(context, true);
this.context = context;
this.myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
if (!PreferencesUtils.getBoolean(
context, R.string.drive_sync_key, PreferencesUtils.DRIVE_SYNC_DEFAULT)) {
return;
}
if (account == null) {
return;
}
String googleAccount = PreferencesUtils.getString(
context, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT);
if (googleAccount == null || googleAccount.equals(PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT)) {
return;
}
if (!googleAccount.equals(account.name)) {
return;
}
try {
GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(
context, account.name, SendToGoogleUtils.DRIVE_SCOPE);
if (credential == null) {
return;
}
if (drive == null || !driveAccountName.equals(account.name)) {
drive = SyncUtils.getDriveService(credential);
driveAccountName = account.name;
}
long largestChangeId = PreferencesUtils.getLong(
context, R.string.drive_largest_change_id_key);
if (largestChangeId == PreferencesUtils.DRIVE_LARGEST_CHANGE_ID_DEFAULT) {
performInitialSync();
} else {
performIncrementalSync(largestChangeId);
}
insertNewDriveFiles();
} catch (UserRecoverableAuthException e) {
SendToGoogleUtils.sendNotification(
context, account.name, e.getIntent(), SendToGoogleUtils.DRIVE_NOTIFICATION_ID);
} catch (GoogleAuthException e) {
Log.e(TAG, "GoogleAuthException", e);
} catch (UserRecoverableAuthIOException e) {
SendToGoogleUtils.sendNotification(
context, account.name, e.getIntent(), SendToGoogleUtils.DRIVE_NOTIFICATION_ID);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
/**
* Gets the folder id..
*/
private String getFolderId() throws IOException {
if (folderId == null) {
File folder = SyncUtils.getMyTracksFolder(context, drive);
if (folder == null) {
throw new IOException("folder is null");
}
folderId = folder.getId();
if (folderId == null) {
throw new IOException("folder id is null");
}
}
return folderId;
}
/**
* Performs initial sync.
*/
private void performInitialSync() throws IOException {
// Get the largest change id first to avoid race conditions
About about = drive.about().get().setFields(ABOUT_GET_FIELDS).execute();
long largestChangeId = about.getLargestChangeId();
// Get all the KML/KMZ files in the "My Drive:/My Tracks" folder
Files.List myTracksFolderRequest = drive.files().list()
.setQ(String.format(Locale.US, SyncUtils.MY_TRACKS_FOLDER_FILES_QUERY, getFolderId()));
Map<String, File> myTracksFolderMap = getFiles(myTracksFolderRequest, true);
// Handle tracks that are already uploaded to Google Drive
Set<String> syncedDriveIds = updateSyncedTracks();
for (String driveId : syncedDriveIds) {
myTracksFolderMap.remove(driveId);
}
// Get all the KML/KMZ files in the "Shared with me:/" folder
Files.List sharedWithMeRequest = drive.files()
.list().setQ(SyncUtils.SHARED_WITH_ME_FILES_QUERY);
Map<String, File> sharedWithMeMap = getFiles(sharedWithMeRequest, false);
try {
insertNewTracks(myTracksFolderMap.values());
insertNewTracks(sharedWithMeMap.values());
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, largestChangeId);
} catch (IOException e) {
// Remove all imported tracks
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
if (!syncedDriveIds.contains(track.getDriveId())) {
myTracksProviderUtils.deleteTrack(context, track.getId());
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
throw e;
}
}
/**
* Updates synced tracks.
*
* @return drive ids of the synced tracks
*/
private Set<String> updateSyncedTracks() throws IOException {
Set<String> result = new HashSet<String>();
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
String driveId = track.getDriveId();
if (driveId != null && !driveId.equals("")) {
if (!track.isSharedWithMe()) {
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())) {
merge(track, driveFile);
result.add(driveId);
} else {
/*
* Track has a drive id, but the drive id is no longer valid.
* E.g., the file is moved to another folder. Clear the drive
* id.
*/
SyncUtils.updateTrack(myTracksProviderUtils, track, null);
}
}
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* Performs incremental sync.
*
* @param largestChangeId the largest change id
*/
private void performIncrementalSync(long largestChangeId) throws IOException {
// Handle deleted tracks
String driveDeletedList = PreferencesUtils.getString(
context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT);
if (!PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT.equals(driveDeletedList)) {
String deletedIds[] = TextUtils.split(driveDeletedList, ";");
for (String driveId : deletedIds) {
deleteDriveFile(driveId, true);
}
PreferencesUtils.setString(
context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT);
}
// Handle edited tracks
String driveEditedList = PreferencesUtils.getString(
context, R.string.drive_edited_list_key, PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT);
if (!PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT.equals(driveEditedList)) {
String editedIds[] = TextUtils.split(driveEditedList, ";");
for (String id : editedIds) {
Track track = myTracksProviderUtils.getTrack(Long.valueOf(id));
if (track == null) {
continue;
}
if (track.isSharedWithMe()) {
continue;
}
String driveId = track.getDriveId();
if (driveId == null || driveId.equals("")) {
continue;
}
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())) {
merge(track, driveFile);
}
}
PreferencesUtils.setString(
context, R.string.drive_edited_list_key, PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT);
}
// Handle changes from Google Drive
Map<String, File> changes = new HashMap<String, File>();
long newLargestChangeId = getDriveChangesInfo(largestChangeId, changes);
if (newLargestChangeId != largestChangeId) {
Cursor cursor = null;
try {
// Get all the local tracks with drive file id
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_ID_TRACKS_QUERY, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
String driveId = track.getDriveId();
if (changes.containsKey(driveId)) {
// Track has changed
File driveFile = changes.get(driveId);
if (driveFile == null) {
Log.d(TAG, "Delete local track " + track.getName());
myTracksProviderUtils.deleteTrack(context, track.getId());
} else {
if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())
|| SyncUtils.isInSharedWithMe(driveFile)) {
merge(track, driveFile);
} else {
SyncUtils.updateTrack(myTracksProviderUtils, track, null);
}
}
changes.remove(driveId);
}
} while (cursor.moveToNext());
}
// Insert valid new drive file changes as new tracks
Iterator<String> iterator = changes.keySet().iterator();
while (iterator.hasNext()) {
String driveId = iterator.next();
File file = changes.get(driveId);
if (!SyncUtils.isInMyTracksAndValid(file, getFolderId())
&& !SyncUtils.isInSharedWithMeAndValid(file)) {
iterator.remove();
}
}
insertNewTracks(changes.values());
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, newLargestChangeId);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
/**
* Inserts new drive files from tracks without a drive id.
*/
private void insertNewDriveFiles() throws IOException {
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.NO_DRIVE_ID_TRACKS_QUERY, null, null);
long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key);
if (cursor != null && cursor.moveToFirst()) {
do {
Track track = myTracksProviderUtils.createTrack(cursor);
if (track.getId() == recordingTrackId) {
continue;
}
// If not successful, the next sync will retry again
SyncUtils.insertDriveFile(
drive, getFolderId(), context, myTracksProviderUtils, track, true);
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/**
* Inserts new tracks from a collection of drive files.
*
* @param driveFiles the drive files
*/
private void insertNewTracks(Collection<File> driveFiles) throws IOException {
for (File driveFile : driveFiles) {
if (driveFile == null) {
return;
}
updateTrack(-1L, driveFile);
}
}
/**
* Gets all the files from a request.
*
* @param request the request
* @param excludeSharedWithMe true to exclude shared with me files
* @return a map of file id to file
*/
private Map<String, File> getFiles(Files.List request, boolean excludeSharedWithMe)
throws IOException {
Map<String, File> idToFileMap = new HashMap<String, File>();
do {
FileList files = request.execute();
for (File file : files.getItems()) {
if (excludeSharedWithMe && file.getSharedWithMeDate() != null) {
continue;
}
idToFileMap.put(file.getId(), file);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
return idToFileMap;
}
/**
* Gets the drive changes info in the My Tracks folder, including deleted files.
*
* @param changeId the largest change id
* @param changes a map of drive id to file for the changes
* @return an updated largest change id
*/
private long getDriveChangesInfo(long changeId, Map<String, File> changes)
throws IOException {
Changes.List request = drive.changes().list().setStartChangeId(changeId + 1);
do {
ChangeList changeList = request.execute();
long newId = changeList.getLargestChangeId().longValue();
for (Change change : changeList.getItems()) {
if (change.getDeleted()) {
changes.put(change.getFileId(), null);
} else {
File file = change.getFile();
if (file.getLabels().getTrashed()) {
changes.put(change.getFileId(), null);
} else {
changes.put(change.getFileId(), file);
}
}
}
if (newId > changeId) {
changeId = newId;
}
request.setPageToken(changeList.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
Log.d(TAG, "Got drive changes: " + changes.size() + " " + changeId);
return changeId;
}
/**
* Merges a track with a drive file.
*
* @param track the track
* @param driveFile the drive file
*/
private void merge(Track track, File driveFile) throws IOException {
long modifiedTime = track.getModifiedTime();
long driveModifiedTime = driveFile.getModifiedDate().getValue();
if (modifiedTime > driveModifiedTime) {
Log.d(TAG, "Updating track change for track " + track.getName() + " and drive file "
+ driveFile.getTitle());
if (!SyncUtils.updateDriveFile(
drive, driveFile, context, myTracksProviderUtils, track, true)) {
Log.e(TAG, "Unable to update drive file");
track.setModifiedTime(driveModifiedTime);
myTracksProviderUtils.updateTrack(track);
}
} else if (modifiedTime < driveModifiedTime) {
Log.d(TAG, "Updating drive change for track " + track.getName() + " and drive file "
+ driveFile.getTitle());
if (!updateTrack(track.getId(), driveFile)) {
Log.e(TAG, "Unable to update drive change");
// The track could have been deleted in the unsuccessful update
track = myTracksProviderUtils.getTrack(track.getId());
if (track != null) {
track.setModifiedTime(driveModifiedTime);
myTracksProviderUtils.updateTrack(track);
}
}
}
}
/**
* Updates a track based on a drive file. Returns true if successful.
*
* @param trackId the track id. -1L to insert a new track
* @param driveFile the drive file
*/
private boolean updateTrack(final long trackId, File driveFile) throws IOException {
Track track = null;
boolean success = false;
try {
track = importDriveFile(trackId, driveFile);
if (track == null) {
return false;
}
File updatedDriveFile;
String trackName = FileUtils.getName(driveFile.getTitle());
if (SyncUtils.isInMyTracks(driveFile, getFolderId()) && !track.getName().equals(trackName)) {
track.setName(trackName);
/*
* The drive file title and the track name inside the drive file do not
* match, update the drive file.
*/
java.io.File file = null;
try {
file = SyncUtils.getTempFile(context, myTracksProviderUtils, track, true);
updatedDriveFile = SyncUtils.updateDriveFile(
drive, driveFile, trackName + "." + KmzTrackExporter.KMZ_EXTENSION, file, true);
if (updatedDriveFile == null) {
Log.e(TAG, "Unable to update drive file");
return false;
}
} finally {
if (file != null) {
file.delete();
}
}
} else {
updatedDriveFile = driveFile;
}
SyncUtils.updateTrack(myTracksProviderUtils, track, updatedDriveFile);
success = true;
return true;
} finally {
if (!success) {
// if the track is new, delete it
if (trackId == -1L && track != null) {
myTracksProviderUtils.deleteTrack(context, track.getId());
}
}
}
}
/**
* Imports drive file to track.
*
* @param trackId the track id. -1L to insert a new track
* @param driveFile the drive file
*/
private Track importDriveFile(long trackId, File driveFile) throws IOException {
InputStream inputStream = null;
try {
inputStream = downloadDriveFile(driveFile, true);
if (inputStream == null) {
Log.e(TAG, "Unable to import drive file. Input stream is null.");
return null;
}
TrackImporter trackImporter;
boolean useKmz = KmzTrackExporter.KMZ_EXTENSION.equals(driveFile.getFileExtension());
if (useKmz) {
if (trackId == -1L) {
Uri uri = myTracksProviderUtils.insertTrack(new Track());
trackId = Long.parseLong(uri.getLastPathSegment());
}
trackImporter = new KmzTrackImporter(context, trackId);
} else {
trackImporter = new KmlFileTrackImporter(context, trackId);
}
long importedId = trackImporter.importFile(inputStream);
if (importedId == -1L) {
Log.e(TAG, "Unable to import drive file. Imported id is -1L.");
return null;
}
Track track = myTracksProviderUtils.getTrack(importedId);
if (track == null) {
Log.e(TAG, "Unable to import drive file. Imported track is null.");
return null;
} else {
return track;
}
} catch (IOException e) {
Log.e(TAG, "Unable to import drive file.", e);
return null;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
/**
* Deletes a drive file.
*
* @param driveId the drive id
* @param canRetry true if can retry the request
* @throws IOException
*/
private void deleteDriveFile(String driveId, boolean canRetry)
throws IOException {
try {
File driveFile = drive.files().get(driveId).execute();
if (SyncUtils.isInMyTracks(driveFile, getFolderId())) {
if (!driveFile.getLabels().getTrashed()) {
drive.files().trash(driveId).execute();
}
// if trashed, ignore
} else if (SyncUtils.isInSharedWithMe(driveFile)) {
if (!driveFile.getLabels().getTrashed()) {
drive.files().delete(driveId).execute();
}
// if trashed, ignore
}
} catch (UserRecoverableAuthIOException e) {
throw e;
} catch (IOException e) {
if (canRetry) {
deleteDriveFile(driveId, false);
return;
}
Log.e(TAG, "Unable to delete Drive file for " + driveId, e);
}
}
/**
* Downloads a drive file.
*
* @param driveFile the drive file
*/
private InputStream downloadDriveFile(File driveFile, boolean canRetry) throws IOException {
if (driveFile.getDownloadUrl() == null || driveFile.getDownloadUrl().length() == 0) {
Log.d(TAG, "Drive file download url doesn't exist: " + driveFile.getTitle());
return null;
}
try {
HttpResponse httpResponse = drive.getRequestFactory()
.buildGetRequest(new GenericUrl(driveFile.getDownloadUrl())).execute();
if (httpResponse == null) {
Log.e(TAG, "http response is null");
return null;
}
return httpResponse.getContent();
} catch (UserRecoverableAuthIOException e) {
throw e;
} catch (IOException e) {
if (canRetry) {
return downloadDriveFile(driveFile, false);
}
throw e;
}
}
}
| Bug fix, do not cache folder id across sync requests to handle the case of switching account
| MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java | Bug fix, do not cache folder id across sync requests to handle the case of switching account | <ide><path>yTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java
<ide> private Drive drive;
<ide> private String driveAccountName; // the account name associated with the drive
<ide> private String folderId;
<del>
<add>
<ide> public SyncAdapter(Context context) {
<ide> super(context, true);
<ide> this.context = context;
<ide> drive = SyncUtils.getDriveService(credential);
<ide> driveAccountName = account.name;
<ide> }
<add> folderId = getFolderId();
<ide>
<ide> long largestChangeId = PreferencesUtils.getLong(
<ide> context, R.string.drive_largest_change_id_key);
<ide> * Gets the folder id..
<ide> */
<ide> private String getFolderId() throws IOException {
<del> if (folderId == null) {
<del> File folder = SyncUtils.getMyTracksFolder(context, drive);
<del> if (folder == null) {
<del> throw new IOException("folder is null");
<del> }
<del> folderId = folder.getId();
<del> if (folderId == null) {
<del> throw new IOException("folder id is null");
<del> }
<del> }
<del> return folderId;
<add> File folder = SyncUtils.getMyTracksFolder(context, drive);
<add> if (folder == null) {
<add> throw new IOException("folder is null");
<add> }
<add> String id = folder.getId();
<add> if (id == null) {
<add> throw new IOException("folder id is null");
<add> }
<add> return id;
<ide> }
<ide>
<ide> /**
<ide> long largestChangeId = about.getLargestChangeId();
<ide>
<ide> // Get all the KML/KMZ files in the "My Drive:/My Tracks" folder
<del> Files.List myTracksFolderRequest = drive.files().list()
<del> .setQ(String.format(Locale.US, SyncUtils.MY_TRACKS_FOLDER_FILES_QUERY, getFolderId()));
<add> Files.List myTracksFolderRequest = drive.files()
<add> .list().setQ(String.format(Locale.US, SyncUtils.MY_TRACKS_FOLDER_FILES_QUERY, folderId));
<ide> Map<String, File> myTracksFolderMap = getFiles(myTracksFolderRequest, true);
<ide>
<ide> // Handle tracks that are already uploaded to Google Drive
<ide> if (driveId != null && !driveId.equals("")) {
<ide> if (!track.isSharedWithMe()) {
<ide> File driveFile = drive.files().get(driveId).execute();
<del> if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())) {
<add> if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)) {
<ide> merge(track, driveFile);
<ide> result.add(driveId);
<ide> } else {
<ide> continue;
<ide> }
<ide> File driveFile = drive.files().get(driveId).execute();
<del> if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())) {
<add> if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)) {
<ide> merge(track, driveFile);
<ide> }
<ide> }
<ide> PreferencesUtils.setString(
<ide> context, R.string.drive_edited_list_key, PreferencesUtils.DRIVE_EDITED_LIST_DEFAULT);
<ide> }
<del>
<add>
<ide> // Handle changes from Google Drive
<ide> Map<String, File> changes = new HashMap<String, File>();
<ide> long newLargestChangeId = getDriveChangesInfo(largestChangeId, changes);
<ide> Log.d(TAG, "Delete local track " + track.getName());
<ide> myTracksProviderUtils.deleteTrack(context, track.getId());
<ide> } else {
<del> if (SyncUtils.isInMyTracksAndValid(driveFile, getFolderId())
<add> if (SyncUtils.isInMyTracksAndValid(driveFile, folderId)
<ide> || SyncUtils.isInSharedWithMe(driveFile)) {
<ide> merge(track, driveFile);
<ide> } else {
<ide> while (iterator.hasNext()) {
<ide> String driveId = iterator.next();
<ide> File file = changes.get(driveId);
<del> if (!SyncUtils.isInMyTracksAndValid(file, getFolderId())
<add> if (!SyncUtils.isInMyTracksAndValid(file, folderId)
<ide> && !SyncUtils.isInSharedWithMeAndValid(file)) {
<ide> iterator.remove();
<ide> }
<ide> continue;
<ide> }
<ide> // If not successful, the next sync will retry again
<del> SyncUtils.insertDriveFile(
<del> drive, getFolderId(), context, myTracksProviderUtils, track, true);
<add> SyncUtils.insertDriveFile(drive, folderId, context, myTracksProviderUtils, track, true);
<ide> } while (cursor.moveToNext());
<ide> }
<ide> } finally {
<ide> }
<ide>
<ide> /**
<del> * Gets the drive changes info in the My Tracks folder, including deleted files.
<add> * Gets the drive changes info in the My Tracks folder, including deleted
<add> * files.
<ide> *
<ide> * @param changeId the largest change id
<ide> * @param changes a map of drive id to file for the changes
<ide> * @return an updated largest change id
<ide> */
<del> private long getDriveChangesInfo(long changeId, Map<String, File> changes)
<del> throws IOException {
<add> private long getDriveChangesInfo(long changeId, Map<String, File> changes) throws IOException {
<ide> Changes.List request = drive.changes().list().setStartChangeId(changeId + 1);
<ide> do {
<ide> ChangeList changeList = request.execute();
<ide> }
<ide> File updatedDriveFile;
<ide> String trackName = FileUtils.getName(driveFile.getTitle());
<del> if (SyncUtils.isInMyTracks(driveFile, getFolderId()) && !track.getName().equals(trackName)) {
<add> if (SyncUtils.isInMyTracks(driveFile, folderId) && !track.getName().equals(trackName)) {
<ide> track.setName(trackName);
<ide>
<ide> /*
<ide> if (useKmz) {
<ide> if (trackId == -1L) {
<ide> Uri uri = myTracksProviderUtils.insertTrack(new Track());
<del> trackId = Long.parseLong(uri.getLastPathSegment());
<add> trackId = Long.parseLong(uri.getLastPathSegment());
<ide> }
<ide> trackImporter = new KmzTrackImporter(context, trackId);
<ide> } else {
<ide> *
<ide> * @param driveId the drive id
<ide> * @param canRetry true if can retry the request
<del> * @throws IOException
<del> */
<del> private void deleteDriveFile(String driveId, boolean canRetry)
<del> throws IOException {
<add> * @throws IOException
<add> */
<add> private void deleteDriveFile(String driveId, boolean canRetry) throws IOException {
<ide> try {
<ide> File driveFile = drive.files().get(driveId).execute();
<del> if (SyncUtils.isInMyTracks(driveFile, getFolderId())) {
<add> if (SyncUtils.isInMyTracks(driveFile, folderId)) {
<ide> if (!driveFile.getLabels().getTrashed()) {
<ide> drive.files().trash(driveId).execute();
<ide> } |
|
Java | apache-2.0 | 354f6bffe4a365acd394cd248c67e826c37a691e | 0 | panossot/xnio,xnio/xnio,kabir/xnio,stuartwdouglas/xnio,panossot/xnio,xnio/xnio,dmlloyd/xnio,kabir/xnio,fl4via/xnio,fl4via/xnio | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.xnio;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.xnio._private.Messages.msg;
/**
* A strongly-typed option to configure an aspect of a service or connection. Options are immutable and use identity comparisons
* and hash codes. Options should always be declared as <code>public static final</code> members in order to support serialization.
*
* @param <T> the option value type
*/
public abstract class Option<T> implements Serializable {
private static final long serialVersionUID = -1564427329140182760L;
private final Class<?> declClass;
private final String name;
Option(final Class<?> declClass, final String name) {
if (declClass == null) {
throw msg.nullParameter("declClass");
}
if (name == null) {
throw msg.nullParameter("name");
}
this.declClass = declClass;
this.name = name;
}
/**
* Create an option with a simple type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param type the class of the value associated with this option
* @return the option instance
*/
public static <T> Option<T> simple(final Class<?> declClass, final String name, final Class<T> type) {
return new SingleOption<T>(declClass, name, type);
}
/**
* Create an option with a sequence type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementType the class of the sequence element value associated with this option
* @return the option instance
*/
public static <T> Option<Sequence<T>> sequence(final Class<?> declClass, final String name, final Class<T> elementType) {
return new SequenceOption<T>(declClass, name, elementType);
}
/**
* Create an option with a class type. The class object given may represent any type.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param declType the class object for the type of the class object given
* @param <T> the type of the class object given
* @return the option instance
*/
public static <T> Option<Class<? extends T>> type(final Class<?> declClass, final String name, final Class<T> declType) {
return new TypeOption<T>(declClass, name, declType);
}
/**
* Create an option with a sequence-of-types type. The class object given may represent any type.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementDeclType the class object for the type of the sequence element class object given
* @param <T> the type of the sequence element class object given
* @return the option instance
*/
public static <T> Option<Sequence<Class<? extends T>>> typeSequence(final Class<?> declClass, final String name, final Class<T> elementDeclType) {
return new TypeSequenceOption<T>(declClass, name, elementDeclType);
}
/**
* Get the name of this option.
*
* @return the option name
*/
public String getName() {
return name;
}
/**
* Get a human-readable string representation of this object.
*
* @return the string representation
*/
public String toString() {
return declClass.getName() + "." + name;
}
/**
* Get an option from a string name, using the given classloader. If the classloader is {@code null}, the bootstrap
* classloader will be used.
*
* @param name the option string
* @param classLoader the class loader
* @return the option
* @throws IllegalArgumentException if the given option name is not valid
*/
public static Option<?> fromString(String name, ClassLoader classLoader) throws IllegalArgumentException {
final int lastDot = name.lastIndexOf('.');
if (lastDot == -1) {
throw msg.invalidOptionName(name);
}
final String fieldName = name.substring(lastDot + 1);
final String className = name.substring(0, lastDot);
final Class<?> clazz;
try {
clazz = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException e) {
throw msg.optionClassNotFound(className, classLoader);
}
final Field field;
try {
field = clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
throw msg.noField(fieldName, clazz);
}
final int modifiers = field.getModifiers();
if (! Modifier.isPublic(modifiers)) {
throw msg.fieldNotAccessible(fieldName, clazz);
}
if (! Modifier.isStatic(modifiers)) {
throw msg.fieldNotStatic(fieldName, clazz);
}
final Option<?> option;
try {
option = (Option<?>) field.get(null);
} catch (IllegalAccessException e) {
throw msg.fieldNotAccessible(fieldName, clazz);
}
if (option == null) {
throw msg.invalidNullOption(name);
}
return option;
}
/**
* Return the given object as the type of this option. If the cast could not be completed, an exception is thrown.
*
* @param o the object to cast
* @return the cast object
* @throws ClassCastException if the object is not of a compatible type
*/
public abstract T cast(Object o) throws ClassCastException;
/**
* Return the given object as the type of this option. If the cast could not be completed, an exception is thrown.
*
* @param o the object to cast
* @param defaultVal the value to return if {@code o} is {@code null}
*
* @return the cast object
*
* @throws ClassCastException if the object is not of a compatible type
*/
public final T cast(Object o, T defaultVal) throws ClassCastException {
return o == null ? defaultVal : cast(o);
}
/**
* Parse a string value for this option.
*
* @param string the string
* @param classLoader the class loader to use to parse the value
* @return the parsed value
* @throws IllegalArgumentException if the argument could not be parsed
*/
public abstract T parseValue(String string, ClassLoader classLoader) throws IllegalArgumentException;
/**
* Resolve this instance for serialization.
*
* @return the resolved object
* @throws java.io.ObjectStreamException if the object could not be resolved
*/
protected final Object readResolve() throws ObjectStreamException {
try {
final Field field = declClass.getField(name);
final int modifiers = field.getModifiers();
if (! Modifier.isPublic(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not public)");
}
if (! Modifier.isStatic(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not static)");
}
final Option<?> option = (Option<?>) field.get(null);
if (option == null) {
throw new InvalidObjectException("Invalid null Option");
}
return option;
} catch (NoSuchFieldException e) {
throw new InvalidObjectException("Invalid Option instance (no matching field)");
} catch (IllegalAccessException e) {
throw new InvalidObjectException("Invalid Option instance (Illegal access on field get)");
}
}
/**
* Create a builder for an immutable option set.
*
* @return the builder
*/
public static Option.SetBuilder setBuilder() {
return new Option.SetBuilder();
}
/**
* A builder for an immutable option set.
*/
public static class SetBuilder {
private List<Option<?>> optionSet = new ArrayList<Option<?>>();
SetBuilder() {
}
/**
* Add an option to this set.
*
* @param option the option to add
* @return this builder
*/
public Option.SetBuilder add(Option<?> option) {
if (option == null) {
throw msg.nullParameter("option");
}
optionSet.add(option);
return this;
}
/**
* Add options to this set.
*
* @param option1 the first option to add
* @param option2 the second option to add
* @return this builder
*/
public Option.SetBuilder add(Option<?> option1, Option<?> option2) {
if (option1 == null) {
throw msg.nullParameter("option1");
}
if (option2 == null) {
throw msg.nullParameter("option2");
}
optionSet.add(option1);
optionSet.add(option2);
return this;
}
/**
* Add options to this set.
*
* @param option1 the first option to add
* @param option2 the second option to add
* @param option3 the third option to add
* @return this builder
*/
public Option.SetBuilder add(Option<?> option1, Option<?> option2, Option<?> option3) {
if (option1 == null) {
throw msg.nullParameter("option1");
}
if (option2 == null) {
throw msg.nullParameter("option2");
}
if (option3 == null) {
throw msg.nullParameter("option3");
}
optionSet.add(option1);
optionSet.add(option2);
optionSet.add(option3);
return this;
}
/**
* Add options to this set.
*
* @param options the options to add
* @return this builder
*/
public Option.SetBuilder add(Option<?>... options) {
if (options == null) {
throw msg.nullParameter("options");
}
for (Option<?> option : options) {
add(option);
}
return this;
}
/**
* Add all options from a collection to this set.
*
* @param options the options to add
* @return this builder
*/
public Option.SetBuilder addAll(Collection<Option<?>> options) {
if (options == null) {
throw msg.nullParameter("option");
}
for (Option<?> option : options) {
add(option);
}
return this;
}
/**
* Create the immutable option set instance.
*
* @return the option set
*/
public Set<Option<?>> create() {
return Collections.unmodifiableSet(new LinkedHashSet<Option<?>>(optionSet));
}
}
interface ValueParser<T> {
T parseValue(String string, ClassLoader classLoader) throws IllegalArgumentException;
}
private static final Map<Class<?>, Option.ValueParser<?>> parsers;
private static final Option.ValueParser<?> noParser = new Option.ValueParser<Object>() {
public Object parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
throw msg.noOptionParser();
}
};
static {
final Map<Class<?>, Option.ValueParser<?>> map = new HashMap<Class<?>, Option.ValueParser<?>>();
map.put(Byte.class, new Option.ValueParser<Byte>() {
public Byte parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Byte.decode(string.trim());
}
});
map.put(Short.class, new Option.ValueParser<Short>() {
public Short parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Short.decode(string.trim());
}
});
map.put(Integer.class, new Option.ValueParser<Integer>() {
public Integer parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Integer.decode(string.trim());
}
});
map.put(Long.class, new Option.ValueParser<Long>() {
public Long parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Long.decode(string.trim());
}
});
map.put(String.class, new Option.ValueParser<String>() {
public String parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return string.trim();
}
});
map.put(Boolean.class, new Option.ValueParser<Boolean>() {
public Boolean parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Boolean.valueOf(string.trim());
}
});
map.put(Property.class, new Option.ValueParser<Object>() {
public Object parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
final int idx = string.indexOf('=');
if (idx == -1) {
throw msg.invalidOptionPropertyFormat(string);
}
return Property.of(string.substring(0, idx), string.substring(idx + 1, string.length()));
}
});
parsers = map;
}
static <T> Option.ValueParser<Class<? extends T>> getClassParser(final Class<T> argType) {
return new ValueParser<Class<? extends T>>() {
public Class<? extends T> parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
try {
return Class.forName(string, false, classLoader).asSubclass(argType);
} catch (ClassNotFoundException e) {
throw msg.classNotFound(string, e);
} catch (ClassCastException e) {
throw msg.classNotInstance(string, argType);
}
}
};
}
static <T> Option.ValueParser<T> getEnumParser(final Class<T> enumType) {
return new ValueParser<T>() {
@SuppressWarnings("unchecked")
public T parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return enumType.cast(Enum.valueOf(enumType.asSubclass(Enum.class), string.trim()));
}
};
}
@SuppressWarnings("unchecked")
static <T> Option.ValueParser<T> getParser(final Class<T> argType) {
if (argType.isEnum()) {
return getEnumParser(argType);
} else {
final Option.ValueParser<?> value = parsers.get(argType);
return (Option.ValueParser<T>) (value == null ? noParser : value);
}
}
}
| api/src/main/java/org/xnio/Option.java | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.xnio;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.xnio._private.Messages.msg;
/**
* A strongly-typed option to configure an aspect of a service or connection. Options are immutable and use identity comparisons
* and hash codes. Options should always be declared as <code>public static final</code> members in order to support serialization.
*
* @param <T> the option value type
*/
public abstract class Option<T> implements Serializable {
private static final long serialVersionUID = -1564427329140182760L;
private final Class<?> declClass;
private final String name;
Option(final Class<?> declClass, final String name) {
if (declClass == null) {
throw msg.nullParameter("declClass");
}
if (name == null) {
throw msg.nullParameter("name");
}
this.declClass = declClass;
this.name = name;
}
/**
* Create an option with a simple type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param type the class of the value associated with this option
* @return the option instance
*/
public static <T> Option<T> simple(final Class<?> declClass, final String name, final Class<T> type) {
return new SingleOption<T>(declClass, name, type);
}
/**
* Create an option with a sequence type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementType the class of the sequence element value associated with this option
* @return the option instance
*/
public static <T> Option<Sequence<T>> sequence(final Class<?> declClass, final String name, final Class<T> elementType) {
return new SequenceOption<T>(declClass, name, elementType);
}
/**
* Create an option with a class type. The class object given may represent any type.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param declType the class object for the type of the class object given
* @param <T> the type of the class object given
* @return the option instance
*/
public static <T> Option<Class<? extends T>> type(final Class<?> declClass, final String name, final Class<T> declType) {
return new TypeOption<T>(declClass, name, declType);
}
/**
* Create an option with a sequence-of-types type. The class object given may represent any type.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementDeclType the class object for the type of the sequence element class object given
* @param <T> the type of the sequence element class object given
* @return the option instance
*/
public static <T> Option<Sequence<Class<? extends T>>> typeSequence(final Class<?> declClass, final String name, final Class<T> elementDeclType) {
return new TypeSequenceOption<T>(declClass, name, elementDeclType);
}
/**
* Get the name of this option.
*
* @return the option name
*/
public String getName() {
return name;
}
/**
* Get a human-readable string representation of this object.
*
* @return the string representation
*/
public String toString() {
return declClass.getName() + "." + name;
}
/**
* Get an option from a string name, using the given classloader. If the classloader is {@code null}, the bootstrap
* classloader will be used.
*
* @param name the option string
* @param classLoader the class loader
* @return the option
* @throws IllegalArgumentException if the given option name is not valid
*/
public static Option<?> fromString(String name, ClassLoader classLoader) throws IllegalArgumentException {
final int lastDot = name.lastIndexOf('.');
if (lastDot == -1) {
throw msg.invalidOptionName(name);
}
final String fieldName = name.substring(lastDot + 1);
final String className = name.substring(0, lastDot);
final Class<?> clazz;
try {
clazz = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException e) {
throw msg.optionClassNotFound(className, classLoader);
}
final Field field;
try {
field = clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
throw msg.noField(fieldName, clazz);
}
final int modifiers = field.getModifiers();
if (! Modifier.isPublic(modifiers)) {
throw msg.fieldNotAccessible(fieldName, clazz);
}
if (! Modifier.isStatic(modifiers)) {
throw msg.fieldNotStatic(fieldName, clazz);
}
final Option<?> option;
try {
option = (Option<?>) field.get(null);
} catch (IllegalAccessException e) {
throw msg.fieldNotAccessible(fieldName, clazz);
}
if (option == null) {
throw msg.invalidNullOption(name);
}
return option;
}
/**
* Return the given object as the type of this option. If the cast could not be completed, an exception is thrown.
*
* @param o the object to cast
* @return the cast object
* @throws ClassCastException if the object is not of a compatible type
*/
public abstract T cast(Object o) throws ClassCastException;
/**
* Return the given object as the type of this option. If the cast could not be completed, an exception is thrown.
*
* @param o the object to cast
* @param defaultVal the value to return if {@code o} is {@code null}
*
* @return the cast object
*
* @throws ClassCastException if the object is not of a compatible type
*/
public final T cast(Object o, T defaultVal) throws ClassCastException {
return o == null ? defaultVal : cast(o);
}
/**
* Parse a string value for this option.
*
* @param string the string
* @param classLoader the class loader to use to parse the value
* @return the parsed value
* @throws IllegalArgumentException if the argument could not be parsed
*/
public abstract T parseValue(String string, ClassLoader classLoader) throws IllegalArgumentException;
/**
* Resolve this instance for serialization.
*
* @return the resolved object
* @throws java.io.ObjectStreamException if the object could not be resolved
*/
protected final Object readResolve() throws ObjectStreamException {
try {
final Field field = declClass.getField(name);
final int modifiers = field.getModifiers();
if (! Modifier.isPublic(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not public)");
}
if (! Modifier.isStatic(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not static)");
}
final Option<?> option = (Option<?>) field.get(null);
if (option == null) {
throw new InvalidObjectException("Invalid null Option");
}
return option;
} catch (NoSuchFieldException e) {
throw new InvalidObjectException("Invalid Option instance (no matching field)");
} catch (IllegalAccessException e) {
throw new InvalidObjectException("Invalid Option instance (Illegal access on field get)");
}
}
/**
* Create a builder for an immutable option set.
*
* @return the builder
*/
public static Option.SetBuilder setBuilder() {
return new Option.SetBuilder();
}
/**
* A builder for an immutable option set.
*/
public static class SetBuilder {
private List<Option<?>> optionSet = new ArrayList<Option<?>>();
SetBuilder() {
}
/**
* Add an option to this set.
*
* @param option the option to add
* @return this builder
*/
public Option.SetBuilder add(Option<?> option) {
if (option == null) {
throw msg.nullParameter("option");
}
optionSet.add(option);
return this;
}
/**
* Add all options from a collection to this set.
*
* @param options the options to add
* @return this builder
*/
public Option.SetBuilder addAll(Collection<Option<?>> options) {
if (options == null) {
throw msg.nullParameter("option");
}
for (Option<?> option : options) {
add(option);
}
return this;
}
/**
* Create the immutable option set instance.
*
* @return the option set
*/
public Set<Option<?>> create() {
return Collections.unmodifiableSet(new LinkedHashSet<Option<?>>(optionSet));
}
}
interface ValueParser<T> {
T parseValue(String string, ClassLoader classLoader) throws IllegalArgumentException;
}
private static final Map<Class<?>, Option.ValueParser<?>> parsers;
private static final Option.ValueParser<?> noParser = new Option.ValueParser<Object>() {
public Object parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
throw msg.noOptionParser();
}
};
static {
final Map<Class<?>, Option.ValueParser<?>> map = new HashMap<Class<?>, Option.ValueParser<?>>();
map.put(Byte.class, new Option.ValueParser<Byte>() {
public Byte parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Byte.decode(string.trim());
}
});
map.put(Short.class, new Option.ValueParser<Short>() {
public Short parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Short.decode(string.trim());
}
});
map.put(Integer.class, new Option.ValueParser<Integer>() {
public Integer parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Integer.decode(string.trim());
}
});
map.put(Long.class, new Option.ValueParser<Long>() {
public Long parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Long.decode(string.trim());
}
});
map.put(String.class, new Option.ValueParser<String>() {
public String parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return string.trim();
}
});
map.put(Boolean.class, new Option.ValueParser<Boolean>() {
public Boolean parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return Boolean.valueOf(string.trim());
}
});
map.put(Property.class, new Option.ValueParser<Object>() {
public Object parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
final int idx = string.indexOf('=');
if (idx == -1) {
throw msg.invalidOptionPropertyFormat(string);
}
return Property.of(string.substring(0, idx), string.substring(idx + 1, string.length()));
}
});
parsers = map;
}
static <T> Option.ValueParser<Class<? extends T>> getClassParser(final Class<T> argType) {
return new ValueParser<Class<? extends T>>() {
public Class<? extends T> parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
try {
return Class.forName(string, false, classLoader).asSubclass(argType);
} catch (ClassNotFoundException e) {
throw msg.classNotFound(string, e);
} catch (ClassCastException e) {
throw msg.classNotInstance(string, argType);
}
}
};
}
static <T> Option.ValueParser<T> getEnumParser(final Class<T> enumType) {
return new ValueParser<T>() {
@SuppressWarnings("unchecked")
public T parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
return enumType.cast(Enum.valueOf(enumType.asSubclass(Enum.class), string.trim()));
}
};
}
@SuppressWarnings("unchecked")
static <T> Option.ValueParser<T> getParser(final Class<T> argType) {
if (argType.isEnum()) {
return getEnumParser(argType);
} else {
final Option.ValueParser<?> value = parsers.get(argType);
return (Option.ValueParser<T>) (value == null ? noParser : value);
}
}
}
| More ways to build option sets
| api/src/main/java/org/xnio/Option.java | More ways to build option sets | <ide><path>pi/src/main/java/org/xnio/Option.java
<ide> }
<ide>
<ide> /**
<add> * Add options to this set.
<add> *
<add> * @param option1 the first option to add
<add> * @param option2 the second option to add
<add> * @return this builder
<add> */
<add> public Option.SetBuilder add(Option<?> option1, Option<?> option2) {
<add> if (option1 == null) {
<add> throw msg.nullParameter("option1");
<add> }
<add> if (option2 == null) {
<add> throw msg.nullParameter("option2");
<add> }
<add> optionSet.add(option1);
<add> optionSet.add(option2);
<add> return this;
<add> }
<add>
<add> /**
<add> * Add options to this set.
<add> *
<add> * @param option1 the first option to add
<add> * @param option2 the second option to add
<add> * @param option3 the third option to add
<add> * @return this builder
<add> */
<add> public Option.SetBuilder add(Option<?> option1, Option<?> option2, Option<?> option3) {
<add> if (option1 == null) {
<add> throw msg.nullParameter("option1");
<add> }
<add> if (option2 == null) {
<add> throw msg.nullParameter("option2");
<add> }
<add> if (option3 == null) {
<add> throw msg.nullParameter("option3");
<add> }
<add> optionSet.add(option1);
<add> optionSet.add(option2);
<add> optionSet.add(option3);
<add> return this;
<add> }
<add>
<add> /**
<add> * Add options to this set.
<add> *
<add> * @param options the options to add
<add> * @return this builder
<add> */
<add> public Option.SetBuilder add(Option<?>... options) {
<add> if (options == null) {
<add> throw msg.nullParameter("options");
<add> }
<add> for (Option<?> option : options) {
<add> add(option);
<add> }
<add> return this;
<add> }
<add>
<add> /**
<ide> * Add all options from a collection to this set.
<ide> *
<ide> * @param options the options to add |
|
Java | mit | error: pathspec 'project/KaryoTyper/src/MedialAxis/RegressionLib.java' did not match any file(s) known to git
| e852cd0005dbba72728482037837a0c3e71a911b | 1 | reatkin2/karyotyper | /**
*
*/
package MedialAxis;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.optimization.fitting.PolynomialFitter;
import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer;
/**
* @author ahkeslin
*
*/
public class RegressionLib {
// This is set after running a regression method in this class.
private double fitError;
public static void main(String[] args) {
try {
int DEGREE = 3;
String inputPath = args[0];
BufferedImage img = ImageIO.read(new File(inputPath));
ArrayList<Point> points = new ArrayList<Point>();
// Read through image for red pixels
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
// Returned integer is really Alpha, Red, Green, Blue with
// each having it's own 8 bits so use AWT's Color class to simplify
Color pixelValue = new Color(img.getRGB(x, y));
int red = pixelValue.getRed();
int green = pixelValue.getGreen();
int blue = pixelValue.getBlue();
// Find red pixels as they represent the medial axis and add
// them to our fitter
if (red > 0 && green < 50 && blue < 50) {
points.add(new Point(x, y));
}
}
}
RegressionLib regressor = new RegressionLib();
DifferentiableUnivariateFunction approximation = regressor.ApproxByPolynomial(DEGREE,
points);
System.out.printf("RMS error: %s\n", regressor.getFitError());
// Opaque pure blue
int PURE_BLUE = 0xff | Color.OPAQUE;
// Write out our new approximation onto the buffer in blue.
for (int x = 0; x < img.getWidth(); x++) {
int y = (int) approximation.value(x);
if (y >= img.getHeight() - 1 || y < 0) {
continue;
}
img.setRGB(x, y, PURE_BLUE);
}
String currentPath = (new File(".")).getCanonicalPath();
String outputPath = currentPath + File.separator + "shapeData" + File.separator
+ "TestData" + File.separator + "TestRegression.png";
File outputFile = new File(outputPath);
ImageIO.write(img, "png", outputFile);
} catch (IOException e) {
System.out.println(e);
}
}
public DifferentiableUnivariateFunction ApproxByPolynomial(int degree,
ArrayList<Point> points) {
LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
PolynomialFitter fitter = new PolynomialFitter(degree, optimizer);
for (Point pt : points) {
fitter.addObservedPoint(pt.x, pt.y);
}
PolynomialFunction approximation = new PolynomialFunction(fitter.fit());
this.setFitError(optimizer.getRMS());
return approximation;
}
public double getFitError() {
return fitError;
}
public void setFitError(double fitError) {
this.fitError = fitError;
}
}
| project/KaryoTyper/src/MedialAxis/RegressionLib.java | Working simple polynomial regression.
| project/KaryoTyper/src/MedialAxis/RegressionLib.java | Working simple polynomial regression. | <ide><path>roject/KaryoTyper/src/MedialAxis/RegressionLib.java
<add>/**
<add> *
<add> */
<add>package MedialAxis;
<add>
<add>import java.awt.Color;
<add>import java.awt.Point;
<add>import java.awt.image.BufferedImage;
<add>import java.io.File;
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>
<add>import javax.imageio.ImageIO;
<add>
<add>import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction;
<add>import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
<add>import org.apache.commons.math3.optimization.fitting.PolynomialFitter;
<add>import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer;
<add>
<add>/**
<add> * @author ahkeslin
<add> *
<add> */
<add>public class RegressionLib {
<add> // This is set after running a regression method in this class.
<add> private double fitError;
<add>
<add> public static void main(String[] args) {
<add> try {
<add> int DEGREE = 3;
<add> String inputPath = args[0];
<add> BufferedImage img = ImageIO.read(new File(inputPath));
<add> ArrayList<Point> points = new ArrayList<Point>();
<add>
<add> // Read through image for red pixels
<add> for (int x = 0; x < img.getWidth(); x++) {
<add> for (int y = 0; y < img.getHeight(); y++) {
<add> // Returned integer is really Alpha, Red, Green, Blue with
<add> // each having it's own 8 bits so use AWT's Color class to simplify
<add> Color pixelValue = new Color(img.getRGB(x, y));
<add> int red = pixelValue.getRed();
<add> int green = pixelValue.getGreen();
<add> int blue = pixelValue.getBlue();
<add>
<add> // Find red pixels as they represent the medial axis and add
<add> // them to our fitter
<add> if (red > 0 && green < 50 && blue < 50) {
<add> points.add(new Point(x, y));
<add> }
<add> }
<add> }
<add>
<add> RegressionLib regressor = new RegressionLib();
<add> DifferentiableUnivariateFunction approximation = regressor.ApproxByPolynomial(DEGREE,
<add> points);
<add> System.out.printf("RMS error: %s\n", regressor.getFitError());
<add>
<add> // Opaque pure blue
<add> int PURE_BLUE = 0xff | Color.OPAQUE;
<add>
<add> // Write out our new approximation onto the buffer in blue.
<add> for (int x = 0; x < img.getWidth(); x++) {
<add>
<add> int y = (int) approximation.value(x);
<add>
<add> if (y >= img.getHeight() - 1 || y < 0) {
<add> continue;
<add> }
<add>
<add> img.setRGB(x, y, PURE_BLUE);
<add> }
<add>
<add> String currentPath = (new File(".")).getCanonicalPath();
<add> String outputPath = currentPath + File.separator + "shapeData" + File.separator
<add> + "TestData" + File.separator + "TestRegression.png";
<add> File outputFile = new File(outputPath);
<add> ImageIO.write(img, "png", outputFile);
<add> } catch (IOException e) {
<add> System.out.println(e);
<add> }
<add> }
<add>
<add> public DifferentiableUnivariateFunction ApproxByPolynomial(int degree,
<add> ArrayList<Point> points) {
<add> LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
<add> PolynomialFitter fitter = new PolynomialFitter(degree, optimizer);
<add>
<add> for (Point pt : points) {
<add> fitter.addObservedPoint(pt.x, pt.y);
<add> }
<add>
<add> PolynomialFunction approximation = new PolynomialFunction(fitter.fit());
<add> this.setFitError(optimizer.getRMS());
<add> return approximation;
<add> }
<add>
<add> public double getFitError() {
<add> return fitError;
<add> }
<add>
<add> public void setFitError(double fitError) {
<add> this.fitError = fitError;
<add> }
<add>} |
|
Java | apache-2.0 | db0a4db0510392331298f7179193ef6c2b4b6053 | 0 | apache/wicket,dashorst/wicket,zwsong/wicket,Servoy/wicket,klopfdreh/wicket,AlienQueen/wicket,klopfdreh/wicket,Servoy/wicket,aldaris/wicket,dashorst/wicket,topicusonderwijs/wicket,selckin/wicket,apache/wicket,bitstorm/wicket,bitstorm/wicket,apache/wicket,klopfdreh/wicket,freiheit-com/wicket,klopfdreh/wicket,zwsong/wicket,aldaris/wicket,apache/wicket,dashorst/wicket,AlienQueen/wicket,freiheit-com/wicket,topicusonderwijs/wicket,mosoft521/wicket,mosoft521/wicket,AlienQueen/wicket,selckin/wicket,astrapi69/wicket,astrapi69/wicket,martin-g/wicket-osgi,apache/wicket,mafulafunk/wicket,zwsong/wicket,bitstorm/wicket,topicusonderwijs/wicket,selckin/wicket,mafulafunk/wicket,mosoft521/wicket,martin-g/wicket-osgi,dashorst/wicket,Servoy/wicket,aldaris/wicket,dashorst/wicket,astrapi69/wicket,topicusonderwijs/wicket,selckin/wicket,AlienQueen/wicket,martin-g/wicket-osgi,aldaris/wicket,mosoft521/wicket,selckin/wicket,mafulafunk/wicket,mosoft521/wicket,freiheit-com/wicket,freiheit-com/wicket,topicusonderwijs/wicket,freiheit-com/wicket,astrapi69/wicket,zwsong/wicket,Servoy/wicket,aldaris/wicket,klopfdreh/wicket,AlienQueen/wicket,bitstorm/wicket,Servoy/wicket,bitstorm/wicket | /*
* $Id$ $Revision:
* 1.20 $ $Date$
*
* ==============================================================================
* 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 wicket.examples.forminput;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import wicket.examples.WicketExamplePage;
import wicket.extensions.markup.html.datepicker.DatePicker;
import wicket.markup.html.WebMarkupContainer;
import wicket.markup.html.form.CheckBox;
import wicket.markup.html.form.ChoiceRenderer;
import wicket.markup.html.form.DropDownChoice;
import wicket.markup.html.form.Form;
import wicket.markup.html.form.ImageButton;
import wicket.markup.html.form.ListMultipleChoice;
import wicket.markup.html.form.RadioChoice;
import wicket.markup.html.form.RequiredTextField;
import wicket.markup.html.form.TextField;
import wicket.markup.html.form.validation.IntegerValidator;
import wicket.markup.html.form.validation.RequiredValidator;
import wicket.markup.html.image.Image;
import wicket.markup.html.link.Link;
import wicket.markup.html.list.ListItem;
import wicket.markup.html.list.ListView;
import wicket.markup.html.panel.FeedbackPanel;
import wicket.model.CompoundPropertyModel;
import wicket.model.Model;
import wicket.model.PropertyModel;
import wicket.protocol.http.WebRequest;
import wicket.util.convert.IConverter;
/**
* Example for form input.
*
* @author Eelco Hillenius
* @author Jonathan Locke
*/
public class FormInput extends WicketExamplePage
{
/** Relevant locales wrapped in a list. */
private static final List LOCALES = Arrays.asList(new Locale[]
{ Locale.ENGLISH, new Locale("nl"), Locale.GERMAN , Locale.SIMPLIFIED_CHINESE });
/** available numbers for the radio selection. */
static final List NUMBERS = Arrays.asList(new String[] { "1", "2", "3" });
/** available sites for the multiple select. */
private static final List SITES = Arrays.asList(new String[] {
"The Server Side", "Java Lobby", "Java.Net" });
/**
* Constructor
*/
public FormInput()
{
Locale locale = getLocale();
// Construct form and feedback panel and hook them up
final FeedbackPanel feedback = new FeedbackPanel("feedback");
add(feedback);
add(new InputForm("inputForm"));
}
/**
* Sets locale for the user's session (getLocale() is inherited from
* Component)
*
* @param locale
* The new locale
*/
public void setLocale(Locale locale)
{
if (locale != null)
{
getSession().setLocale(locale);
}
}
/**
* Form for collecting input.
*/
private class InputForm extends Form
{
/**
* Construct.
*
* @param name
* Component name
*/
public InputForm(String name)
{
super(name, new CompoundPropertyModel(new FormInputModel()));
// Dropdown for selecting locale
add(new LocaleDropDownChoice("localeSelect"));
// Link to return to default locale
add(new Link("defaultLocaleLink")
{
public void onClick()
{
WebRequest request = (WebRequest)getRequest();
setLocale(request.getLocale());
}
});
RequiredTextField stringTextField = new RequiredTextField("stringProperty");
stringTextField.setLabel(new Model("String"));
add(stringTextField);
RequiredTextField integerTextField = new RequiredTextField("integerProperty", Integer.class);
add(integerTextField);
add(new RequiredTextField("doubleProperty", Double.class));
// we have a component attached to the label here, as we want to synchronize the
// id's of the label, textfield and datepicker. Note that you can perfectly
// do without labels
WebMarkupContainer dateLabel = new WebMarkupContainer("dateLabel");
add(dateLabel);
TextField datePropertyTextField = new TextField("dateProperty", Date.class);
add(datePropertyTextField);
add(new DatePicker("datePicker", dateLabel, datePropertyTextField));
add(new RequiredTextField("integerInRangeProperty", Integer.class).add(
IntegerValidator.range(0, 100)));
add(new CheckBox("booleanProperty"));
RadioChoice rc = new RadioChoice("numberRadioChoice", NUMBERS).setSuffix("");
rc.setLabel(new Model("number"));
rc.add(RequiredValidator.getInstance());
add(rc);
add(new ListMultipleChoice("siteSelection", SITES));
// as an example, we use a custom converter here.
add(new TextField("urlProperty", URL.class)
{
public IConverter getConverter()
{
return new URLConverter();
}
});
// and this is to show we can nest ListViews in Forms too
add(new LinesListView("lines"));
add(new ImageButton("saveButton"));
add(new Link("resetButtonLink")
{
public void onClick()
{
// just call modelChanged so that any invalid input is
// cleared.
InputForm.this.modelChanged();
}
}.add(new Image("resetButtonImage")));
}
/**
* @see wicket.markup.html.form.Form#onSubmit()
*/
public void onSubmit()
{
// Form validation successful. Display message showing edited model.
info("Saved model " + getModelObject());
}
}
/**
* Dropdown with Locales.
*/
private final class LocaleDropDownChoice extends DropDownChoice
{
/**
* Construct.
*
* @param id
* component id
*/
public LocaleDropDownChoice(String id)
{
super(id, LOCALES, new LocaleChoiceRenderer());
// set the model that gets the current locale, and that is used for
// updating the current locale to property 'locale' of FormInput
setModel(new PropertyModel(FormInput.this, "locale"));
}
/**
* @see wicket.markup.html.form.DropDownChoice#wantOnSelectionChangedNotifications()
*/
protected boolean wantOnSelectionChangedNotifications()
{
// we want roundtrips when a the user selects another item
return true;
}
/**
* @see wicket.markup.html.form.DropDownChoice#onSelectionChanged(java.lang.Object)
*/
public void onSelectionChanged(Object newSelection)
{
// note that we don't have to do anything here, as our property
// model allready calls FormInput.setLocale when the model is updated
// setLocale((Locale)newSelection); // so we don't need to do this
}
}
/**
* Choice for a locale.
*/
private final class LocaleChoiceRenderer extends ChoiceRenderer
{
/**
* Constructor.
*/
public LocaleChoiceRenderer()
{
}
/**
* @see wicket.markup.html.form.IChoiceRenderer#getDisplayValue(Object)
*/
public Object getDisplayValue(Object object)
{
Locale locale = (Locale)object;
String display = locale.getDisplayName(getLocale());
return display;
}
}
/** list view to be nested in the form. */
private static final class LinesListView extends ListView
{
/**
* Construct.
*
* @param id
*/
public LinesListView(String id)
{
super(id);
// always do this in forms!
setOptimizeItemRemoval(true);
}
protected void populateItem(ListItem item)
{
// add a text field that works on each list item model (returns objects of
// type FormInputModel.Line) using property text.
item.add(new TextField("lineEdit", new PropertyModel(item.getModel(), "text")));
}
}
} | wicket-examples/src/java/wicket/examples/forminput/FormInput.java | /*
* $Id$ $Revision:
* 1.20 $ $Date$
*
* ==============================================================================
* 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 wicket.examples.forminput;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import wicket.examples.WicketExamplePage;
import wicket.extensions.markup.html.datepicker.DatePicker;
import wicket.markup.html.WebMarkupContainer;
import wicket.markup.html.form.CheckBox;
import wicket.markup.html.form.ChoiceRenderer;
import wicket.markup.html.form.DropDownChoice;
import wicket.markup.html.form.Form;
import wicket.markup.html.form.ImageButton;
import wicket.markup.html.form.ListMultipleChoice;
import wicket.markup.html.form.RadioChoice;
import wicket.markup.html.form.RequiredTextField;
import wicket.markup.html.form.TextField;
import wicket.markup.html.form.validation.IntegerValidator;
import wicket.markup.html.form.validation.RequiredValidator;
import wicket.markup.html.image.Image;
import wicket.markup.html.link.Link;
import wicket.markup.html.list.ListItem;
import wicket.markup.html.list.ListView;
import wicket.markup.html.panel.FeedbackPanel;
import wicket.model.CompoundPropertyModel;
import wicket.model.Model;
import wicket.model.PropertyModel;
import wicket.protocol.http.WebRequest;
import wicket.util.convert.IConverter;
/**
* Example for form input.
*
* @author Eelco Hillenius
* @author Jonathan Locke
*/
public class FormInput extends WicketExamplePage
{
/** Relevant locales wrapped in a list. */
private static final List LOCALES = Arrays.asList(new Locale[]
{ Locale.ENGLISH, new Locale("nl"), Locale.GERMAN , Locale.SIMPLIFIED_CHINESE });
/** available numbers for the radio selection. */
static final List NUMBERS = Arrays.asList(new String[] { "1", "2", "3" });
/** available sites for the multiple select. */
private static final List SITES = Arrays.asList(new String[] {
"The Server Side", "Java Lobby", "Java.Net" });
/**
* Constructor
*/
public FormInput()
{
Locale locale = getLocale();
// Construct form and feedback panel and hook them up
final FeedbackPanel feedback = new FeedbackPanel("feedback");
add(feedback);
add(new InputForm("inputForm"));
}
/**
* Sets locale for the user's session (getLocale() is inherited from
* Component)
*
* @param locale
* The new locale
*/
public void setLocale(Locale locale)
{
getSession().setLocale(locale);
}
/**
* Form for collecting input.
*/
private class InputForm extends Form
{
/**
* Construct.
*
* @param name
* Component name
*/
public InputForm(String name)
{
super(name, new CompoundPropertyModel(new FormInputModel()));
// Dropdown for selecting locale
add(new LocaleDropDownChoice("localeSelect"));
// Link to return to default locale
add(new Link("defaultLocaleLink")
{
public void onClick()
{
WebRequest request = (WebRequest)getRequest();
setLocale(request.getLocale());
}
});
RequiredTextField stringTextField = new RequiredTextField("stringProperty");
stringTextField.setLabel(new Model("String"));
add(stringTextField);
RequiredTextField integerTextField = new RequiredTextField("integerProperty", Integer.class);
add(integerTextField);
add(new RequiredTextField("doubleProperty", Double.class));
// we have a component attached to the label here, as we want to synchronize the
// id's of the label, textfield and datepicker. Note that you can perfectly
// do without labels
WebMarkupContainer dateLabel = new WebMarkupContainer("dateLabel");
add(dateLabel);
TextField datePropertyTextField = new TextField("dateProperty", Date.class);
add(datePropertyTextField);
add(new DatePicker("datePicker", dateLabel, datePropertyTextField));
add(new RequiredTextField("integerInRangeProperty", Integer.class).add(
IntegerValidator.range(0, 100)));
add(new CheckBox("booleanProperty"));
RadioChoice rc = new RadioChoice("numberRadioChoice", NUMBERS).setSuffix("");
rc.setLabel(new Model("number"));
rc.add(RequiredValidator.getInstance());
add(rc);
add(new ListMultipleChoice("siteSelection", SITES));
// as an example, we use a custom converter here.
add(new TextField("urlProperty", URL.class)
{
public IConverter getConverter()
{
return new URLConverter();
}
});
// and this is to show we can nest ListViews in Forms too
add(new LinesListView("lines"));
add(new ImageButton("saveButton"));
add(new Link("resetButtonLink")
{
public void onClick()
{
// just call modelChanged so that any invalid input is
// cleared.
InputForm.this.modelChanged();
}
}.add(new Image("resetButtonImage")));
}
/**
* @see wicket.markup.html.form.Form#onSubmit()
*/
public void onSubmit()
{
// Form validation successful. Display message showing edited model.
info("Saved model " + getModelObject());
}
}
/**
* Dropdown with Locales.
*/
private final class LocaleDropDownChoice extends DropDownChoice
{
/**
* Construct.
*
* @param id
* component id
*/
public LocaleDropDownChoice(String id)
{
super(id, LOCALES, new LocaleChoiceRenderer());
// set the model that gets the current locale, and that is used for
// updating the current locale to property 'locale' of FormInput
setModel(new PropertyModel(FormInput.this, "locale"));
}
/**
* @see wicket.markup.html.form.DropDownChoice#wantOnSelectionChangedNotifications()
*/
protected boolean wantOnSelectionChangedNotifications()
{
// we want roundtrips when a the user selects another item
return true;
}
/**
* @see wicket.markup.html.form.DropDownChoice#onSelectionChanged(java.lang.Object)
*/
public void onSelectionChanged(Object newSelection)
{
// note that we don't have to do anything here, as our property
// model allready calls FormInput.setLocale when the model is updated
// setLocale((Locale)newSelection); // so we don't need to do this
}
}
/**
* Choice for a locale.
*/
private final class LocaleChoiceRenderer extends ChoiceRenderer
{
/**
* Constructor.
*/
public LocaleChoiceRenderer()
{
}
/**
* @see wicket.markup.html.form.IChoiceRenderer#getDisplayValue(Object)
*/
public Object getDisplayValue(Object object)
{
Locale locale = (Locale)object;
String display = locale.getDisplayName(getLocale());
return display;
}
}
/** list view to be nested in the form. */
private static final class LinesListView extends ListView
{
/**
* Construct.
*
* @param id
*/
public LinesListView(String id)
{
super(id);
// always do this in forms!
setOptimizeItemRemoval(true);
}
protected void populateItem(ListItem item)
{
// add a text field that works on each list item model (returns objects of
// type FormInputModel.Line) using property text.
item.add(new TextField("lineEdit", new PropertyModel(item.getModel(), "text")));
}
}
} | avoid NPE
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@459438 13f79535-47bb-0310-9956-ffa450edef68
| wicket-examples/src/java/wicket/examples/forminput/FormInput.java | avoid NPE | <ide><path>icket-examples/src/java/wicket/examples/forminput/FormInput.java
<ide> */
<ide> public void setLocale(Locale locale)
<ide> {
<del> getSession().setLocale(locale);
<add> if (locale != null)
<add> {
<add> getSession().setLocale(locale);
<add> }
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | e7d66b58ea3a21bdcb27dd00f02a97b510a08543 | 0 | xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,apixandru/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ibinti/intellij-community,FHannes/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,semonte/intellij-community,allotria/intellij-community,FHannes/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,allotria/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,asedunov/intellij-community,da1z/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,xfournet/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,semonte/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2015 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.theoryinpractice.testng.inspection;
import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodQuickFix;
import com.intellij.codeInspection.BaseJavaLocalInspectionTool;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateDescriptor;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.util.Version;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.theoryinpractice.testng.DataProviderReference;
import com.theoryinpractice.testng.TestNGFramework;
import com.theoryinpractice.testng.util.TestNGUtil;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.DataProvider;
import java.util.Properties;
public class TestNGDataProviderInspection extends BaseJavaLocalInspectionTool {
@NotNull
@Override
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, final boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitAnnotation(PsiAnnotation annotation) {
if (TestNGUtil.TEST_ANNOTATION_FQN.equals(annotation.getQualifiedName())) {
final PsiAnnotationMemberValue provider = annotation.findDeclaredAttributeValue("dataProvider");
if (provider != null && !TestNGUtil.isDisabled(annotation)) {
for (PsiReference reference : provider.getReferences()) {
if (reference instanceof DataProviderReference) {
final PsiElement dataProviderMethod = reference.resolve();
final PsiElement element = reference.getElement();
final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element);
final PsiClass providerClass = TestNGUtil.getProviderClass(element, topLevelClass);
if (!(dataProviderMethod instanceof PsiMethod)) {
final LocalQuickFix[] fixes;
if (isOnTheFly && providerClass != null) {
fixes = new LocalQuickFix[] {createMethodFix(provider, providerClass, topLevelClass)};
}
else {
fixes = LocalQuickFix.EMPTY_ARRAY;
}
holder.registerProblem(provider, "Data provider does not exist", fixes);
} else {
Version version = TestNGUtil.detectVersion(holder.getProject(), ModuleUtilCore.findModuleForPsiElement(providerClass));
if (version != null && version.isOrGreaterThan(6, 9, 13)) {
break;
}
final PsiMethod providerMethod = (PsiMethod)dataProviderMethod;
if (providerClass != topLevelClass && !providerMethod.hasModifierProperty(PsiModifier.STATIC)) {
holder.registerProblem(provider, "Data provider from foreign class need to be static");
}
}
break;
}
}
}
}
}
};
}
private static CreateMethodQuickFix createMethodFix(PsiAnnotationMemberValue provider,
@NotNull PsiClass providerClass,
PsiClass topLevelClass) {
final String name = StringUtil.unquoteString(provider.getText());
FileTemplateDescriptor templateDesc = new TestNGFramework().getParametersMethodFileTemplateDescriptor();
assert templateDesc != null;
final FileTemplate fileTemplate = FileTemplateManager.getInstance(provider.getProject()).getCodeTemplate(templateDesc.getFileName());
String body = "";
try {
final Properties attributes = new Properties();
attributes.put(FileTemplate.ATTRIBUTE_NAME, name);
body = fileTemplate.getText(attributes);
body = body.replace("${BODY}\n", "");
final PsiMethod methodFromTemplate = JavaPsiFacade.getElementFactory(providerClass.getProject()).createMethodFromText(body, providerClass);
final PsiCodeBlock methodBody = methodFromTemplate.getBody();
if (methodBody != null) {
body = StringUtil.trimEnd(StringUtil.trimStart(methodBody.getText(), "{"), "}");
}
else {
body = "";
}
}
catch (Exception ignored) {}
if (StringUtil.isEmptyOrSpaces(body)) {
body = "return new Object[][]{};";
}
String signature = "@" + DataProvider.class.getName() + " public ";
if (providerClass == topLevelClass) {
signature += "static ";
}
signature += "Object[][] " + name + "()";
return CreateMethodQuickFix.createFix(providerClass, signature, body);
}
}
| plugins/testng/src/com/theoryinpractice/testng/inspection/TestNGDataProviderInspection.java | /*
* Copyright 2000-2015 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.theoryinpractice.testng.inspection;
import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodQuickFix;
import com.intellij.codeInspection.BaseJavaLocalInspectionTool;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateDescriptor;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.theoryinpractice.testng.DataProviderReference;
import com.theoryinpractice.testng.TestNGFramework;
import com.theoryinpractice.testng.util.TestNGUtil;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.DataProvider;
import java.io.IOException;
import java.util.Properties;
public class TestNGDataProviderInspection extends BaseJavaLocalInspectionTool {
@NotNull
@Override
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, final boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitAnnotation(PsiAnnotation annotation) {
if (TestNGUtil.TEST_ANNOTATION_FQN.equals(annotation.getQualifiedName())) {
final PsiAnnotationMemberValue provider = annotation.findDeclaredAttributeValue("dataProvider");
if (provider != null && !TestNGUtil.isDisabled(annotation)) {
for (PsiReference reference : provider.getReferences()) {
if (reference instanceof DataProviderReference) {
final PsiElement dataProviderMethod = reference.resolve();
final PsiElement element = reference.getElement();
final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element);
final PsiClass providerClass = TestNGUtil.getProviderClass(element, topLevelClass);
if (!(dataProviderMethod instanceof PsiMethod)) {
final LocalQuickFix[] fixes;
if (isOnTheFly && providerClass != null) {
fixes = new LocalQuickFix[] {createMethodFix(provider, providerClass, topLevelClass)};
}
else {
fixes = LocalQuickFix.EMPTY_ARRAY;
}
holder.registerProblem(provider, "Data provider does not exist", fixes);
} else {
final PsiMethod providerMethod = (PsiMethod)dataProviderMethod;
if (providerClass != topLevelClass && !providerMethod.hasModifierProperty(PsiModifier.STATIC)) {
holder.registerProblem(provider, "Data provider from foreign class need to be static");
}
}
break;
}
}
}
}
}
};
}
private static CreateMethodQuickFix createMethodFix(PsiAnnotationMemberValue provider,
@NotNull PsiClass providerClass,
PsiClass topLevelClass) {
final String name = StringUtil.unquoteString(provider.getText());
FileTemplateDescriptor templateDesc = new TestNGFramework().getParametersMethodFileTemplateDescriptor();
assert templateDesc != null;
final FileTemplate fileTemplate = FileTemplateManager.getInstance(provider.getProject()).getCodeTemplate(templateDesc.getFileName());
String body = "";
try {
final Properties attributes = new Properties();
attributes.put(FileTemplate.ATTRIBUTE_NAME, name);
body = fileTemplate.getText(attributes);
body = body.replace("${BODY}\n", "");
final PsiMethod methodFromTemplate = JavaPsiFacade.getElementFactory(providerClass.getProject()).createMethodFromText(body, providerClass);
final PsiCodeBlock methodBody = methodFromTemplate.getBody();
if (methodBody != null) {
body = StringUtil.trimEnd(StringUtil.trimStart(methodBody.getText(), "{"), "}");
}
else {
body = "";
}
}
catch (Exception ignored) {}
if (StringUtil.isEmptyOrSpaces(body)) {
body = "return new Object[][]{};";
}
String signature = "@" + DataProvider.class.getName() + " public ";
if (providerClass == topLevelClass) {
signature += "static ";
}
signature += "Object[][] " + name + "()";
return CreateMethodQuickFix.createFix(providerClass, signature, body);
}
}
| testng: accept non-static data provider methods in foreign classes since 6.9.13 (IDEA-171367)
| plugins/testng/src/com/theoryinpractice/testng/inspection/TestNGDataProviderInspection.java | testng: accept non-static data provider methods in foreign classes since 6.9.13 (IDEA-171367) | <ide><path>lugins/testng/src/com/theoryinpractice/testng/inspection/TestNGDataProviderInspection.java
<ide> import com.intellij.ide.fileTemplates.FileTemplate;
<ide> import com.intellij.ide.fileTemplates.FileTemplateDescriptor;
<ide> import com.intellij.ide.fileTemplates.FileTemplateManager;
<add>import com.intellij.openapi.module.ModuleUtilCore;
<add>import com.intellij.openapi.util.Version;
<ide> import com.intellij.openapi.util.text.StringUtil;
<ide> import com.intellij.psi.*;
<ide> import com.intellij.psi.util.PsiUtil;
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.testng.annotations.DataProvider;
<ide>
<del>import java.io.IOException;
<ide> import java.util.Properties;
<ide>
<ide> public class TestNGDataProviderInspection extends BaseJavaLocalInspectionTool {
<ide>
<ide> holder.registerProblem(provider, "Data provider does not exist", fixes);
<ide> } else {
<add> Version version = TestNGUtil.detectVersion(holder.getProject(), ModuleUtilCore.findModuleForPsiElement(providerClass));
<add> if (version != null && version.isOrGreaterThan(6, 9, 13)) {
<add> break;
<add> }
<ide> final PsiMethod providerMethod = (PsiMethod)dataProviderMethod;
<ide> if (providerClass != topLevelClass && !providerMethod.hasModifierProperty(PsiModifier.STATIC)) {
<ide> holder.registerProblem(provider, "Data provider from foreign class need to be static"); |
|
Java | apache-2.0 | ab313005132783be84fe65942ea2ce24652a6a29 | 0 | himanshug/druid,erikdubbelboer/druid,leventov/druid,zhaown/druid,friedhardware/druid,milimetric/druid,kevintvh/druid,du00cs/druid,amikey/druid,lcp0578/druid,amikey/druid,Kleagleguo/druid,du00cs/druid,calliope7/druid,druid-io/druid,qix/druid,zhaown/druid,authbox-lib/druid,767326791/druid,rasahner/druid,michaelschiff/druid,druid-io/druid,minewhat/druid,taochaoqiang/druid,minewhat/druid,eshen1991/druid,potto007/druid-avro,solimant/druid,mrijke/druid,yaochitc/druid-dev,fjy/druid,calliope7/druid,lcp0578/druid,Kleagleguo/druid,amikey/druid,du00cs/druid,deltaprojects/druid,KurtYoung/druid,implydata/druid,zengzhihai110/druid,liquidm/druid,b-slim/druid,calliope7/druid,minewhat/druid,jon-wei/druid,nishantmonu51/druid,wenjixin/druid,zhaown/druid,gianm/druid,minewhat/druid,nishantmonu51/druid,andy256/druid,yaochitc/druid-dev,optimizely/druid,wenjixin/druid,wenjixin/druid,se7entyse7en/druid,optimizely/druid,andy256/druid,Fokko/druid,mghosh4/druid,deltaprojects/druid,jon-wei/druid,michaelschiff/druid,skyportsystems/druid,guobingkun/druid,zhihuij/druid,b-slim/druid,se7entyse7en/druid,tubemogul/druid,smartpcr/druid,metamx/druid,metamx/druid,lizhanhui/data_druid,friedhardware/druid,Fokko/druid,liquidm/druid,tubemogul/druid,pombredanne/druid,premc/druid,767326791/druid,mangeshpardeshiyahoo/druid,gianm/druid,b-slim/druid,andy256/druid,knoguchi/druid,jon-wei/druid,lcp0578/druid,nvoron23/druid,leventov/druid,monetate/druid,mghosh4/druid,se7entyse7en/druid,dkhwangbo/druid,calliope7/druid,deltaprojects/druid,nishantmonu51/druid,eshen1991/druid,pjain1/druid,zhiqinghuang/druid,optimizely/druid,qix/druid,deltaprojects/druid,noddi/druid,Fokko/druid,anupkumardixit/druid,liquidm/druid,fjy/druid,friedhardware/druid,milimetric/druid,anupkumardixit/druid,skyportsystems/druid,redBorder/druid,smartpcr/druid,haoch/druid,taochaoqiang/druid,pjain1/druid,premc/druid,OttoOps/druid,liquidm/druid,monetate/druid,cocosli/druid,mghosh4/druid,liquidm/druid,dkhwangbo/druid,druid-io/druid,nvoron23/druid,zhiqinghuang/druid,pjain1/druid,knoguchi/druid,zhaown/druid,pdeva/druid,nishantmonu51/druid,himanshug/druid,michaelschiff/druid,fjy/druid,dkhwangbo/druid,Deebs21/druid,redBorder/druid,smartpcr/druid,erikdubbelboer/druid,eshen1991/druid,erikdubbelboer/druid,qix/druid,erikdubbelboer/druid,Fokko/druid,Deebs21/druid,praveev/druid,michaelschiff/druid,andy256/druid,pjain1/druid,qix/druid,KurtYoung/druid,Kleagleguo/druid,tubemogul/druid,mangeshpardeshiyahoo/druid,kevintvh/druid,eshen1991/druid,andy256/druid,dclim/druid,guobingkun/druid,deltaprojects/druid,penuel-leo/druid,zengzhihai110/druid,redBorder/druid,gianm/druid,metamx/druid,milimetric/druid,OttoOps/druid,authbox-lib/druid,solimant/druid,zhaown/druid,deltaprojects/druid,taochaoqiang/druid,calliope7/druid,kevintvh/druid,milimetric/druid,mghosh4/druid,druid-io/druid,Kleagleguo/druid,gianm/druid,himanshug/druid,nvoron23/druid,taochaoqiang/druid,qix/druid,zengzhihai110/druid,yaochitc/druid-dev,authbox-lib/druid,zhihuij/druid,dkhwangbo/druid,optimizely/druid,zxs/druid,zxs/druid,mrijke/druid,Kleagleguo/druid,implydata/druid,yaochitc/druid-dev,zhiqinghuang/druid,haoch/druid,zhiqinghuang/druid,metamx/druid,michaelschiff/druid,dclim/druid,monetate/druid,implydata/druid,nvoron23/druid,smartpcr/druid,winval/druid,dclim/druid,monetate/druid,praveev/druid,anupkumardixit/druid,leventov/druid,Deebs21/druid,tubemogul/druid,himanshug/druid,dclim/druid,solimant/druid,michaelschiff/druid,solimant/druid,anupkumardixit/druid,jon-wei/druid,elijah513/druid,KurtYoung/druid,pjain1/druid,fjy/druid,gianm/druid,authbox-lib/druid,michaelschiff/druid,cocosli/druid,noddi/druid,fjy/druid,jon-wei/druid,redBorder/druid,winval/druid,haoch/druid,potto007/druid-avro,767326791/druid,wenjixin/druid,pombredanne/druid,pdeva/druid,winval/druid,lizhanhui/data_druid,767326791/druid,mrijke/druid,b-slim/druid,gianm/druid,mrijke/druid,dkhwangbo/druid,cocosli/druid,milimetric/druid,nishantmonu51/druid,pombredanne/druid,guobingkun/druid,optimizely/druid,praveev/druid,leventov/druid,zxs/druid,pdeva/druid,penuel-leo/druid,kevintvh/druid,Fokko/druid,knoguchi/druid,767326791/druid,lcp0578/druid,penuel-leo/druid,mghosh4/druid,implydata/druid,nvoron23/druid,nishantmonu51/druid,guobingkun/druid,wenjixin/druid,KurtYoung/druid,cocosli/druid,Deebs21/druid,pjain1/druid,friedhardware/druid,noddi/druid,mghosh4/druid,amikey/druid,mghosh4/druid,redBorder/druid,du00cs/druid,yaochitc/druid-dev,solimant/druid,premc/druid,skyportsystems/druid,taochaoqiang/druid,knoguchi/druid,noddi/druid,jon-wei/druid,himanshug/druid,zengzhihai110/druid,pombredanne/druid,pdeva/druid,winval/druid,se7entyse7en/druid,monetate/druid,jon-wei/druid,druid-io/druid,se7entyse7en/druid,potto007/druid-avro,rasahner/druid,rasahner/druid,KurtYoung/druid,pdeva/druid,deltaprojects/druid,lizhanhui/data_druid,knoguchi/druid,lcp0578/druid,implydata/druid,potto007/druid-avro,cocosli/druid,potto007/druid-avro,implydata/druid,kevintvh/druid,lizhanhui/data_druid,skyportsystems/druid,du00cs/druid,b-slim/druid,elijah513/druid,haoch/druid,zhihuij/druid,nishantmonu51/druid,elijah513/druid,zxs/druid,monetate/druid,guobingkun/druid,zhihuij/druid,amikey/druid,Fokko/druid,friedhardware/druid,rasahner/druid,winval/druid,rasahner/druid,mangeshpardeshiyahoo/druid,metamx/druid,anupkumardixit/druid,tubemogul/druid,Fokko/druid,OttoOps/druid,praveev/druid,praveev/druid,pjain1/druid,gianm/druid,elijah513/druid,dclim/druid,zxs/druid,OttoOps/druid,noddi/druid,monetate/druid,skyportsystems/druid,eshen1991/druid,lizhanhui/data_druid,liquidm/druid,smartpcr/druid,premc/druid,zhihuij/druid,elijah513/druid,OttoOps/druid,zengzhihai110/druid,penuel-leo/druid,authbox-lib/druid,mrijke/druid,zhiqinghuang/druid,penuel-leo/druid,premc/druid,haoch/druid,mangeshpardeshiyahoo/druid,minewhat/druid,Deebs21/druid,pombredanne/druid,leventov/druid,erikdubbelboer/druid,mangeshpardeshiyahoo/druid | /*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.server.coordinator;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.inject.Inject;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.concurrent.ScheduledExecutorFactory;
import com.metamx.common.concurrent.ScheduledExecutors;
import com.metamx.common.guava.Comparators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.client.DruidDataSource;
import io.druid.client.DruidServer;
import io.druid.client.ImmutableDruidDataSource;
import io.druid.client.ImmutableDruidServer;
import io.druid.client.ServerInventoryView;
import io.druid.client.indexing.IndexingServiceClient;
import io.druid.collections.CountingMap;
import io.druid.common.config.JacksonConfigManager;
import io.druid.concurrent.Execs;
import io.druid.curator.discovery.ServiceAnnouncer;
import io.druid.db.DatabaseRuleManager;
import io.druid.db.DatabaseSegmentManager;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Self;
import io.druid.segment.IndexIO;
import io.druid.server.DruidNode;
import io.druid.server.coordinator.helper.DruidCoordinatorBalancer;
import io.druid.server.coordinator.helper.DruidCoordinatorCleanup;
import io.druid.server.coordinator.helper.DruidCoordinatorHelper;
import io.druid.server.coordinator.helper.DruidCoordinatorLogger;
import io.druid.server.coordinator.helper.DruidCoordinatorRuleRunner;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentInfoLoader;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentMerger;
import io.druid.server.coordinator.rules.LoadRule;
import io.druid.server.coordinator.rules.Rule;
import io.druid.server.initialization.ZkPathsConfig;
import io.druid.timeline.DataSegment;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.Participant;
import org.apache.curator.utils.ZKPaths;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
/**
*/
@ManageLifecycle
public class DruidCoordinator
{
public static final String COORDINATOR_OWNER_NODE = "_COORDINATOR";
private static final EmittingLogger log = new EmittingLogger(DruidCoordinator.class);
private final Object lock = new Object();
private final DruidCoordinatorConfig config;
private final ZkPathsConfig zkPaths;
private final JacksonConfigManager configManager;
private final DatabaseSegmentManager databaseSegmentManager;
private final ServerInventoryView<Object> serverInventoryView;
private final DatabaseRuleManager databaseRuleManager;
private final CuratorFramework curator;
private final ServiceEmitter emitter;
private final IndexingServiceClient indexingServiceClient;
private final ScheduledExecutorService exec;
private final LoadQueueTaskMaster taskMaster;
private final Map<String, LoadQueuePeon> loadManagementPeons;
private final AtomicReference<LeaderLatch> leaderLatch;
private final ServiceAnnouncer serviceAnnouncer;
private final DruidNode self;
private volatile boolean started = false;
private volatile int leaderCounter = 0;
private volatile boolean leader = false;
private volatile SegmentReplicantLookup segmentReplicantLookup = null;
@Inject
public DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
@Self DruidNode self
)
{
this(
config,
zkPaths,
configManager,
databaseSegmentManager,
serverInventoryView,
databaseRuleManager,
curator,
emitter,
scheduledExecutorFactory,
indexingServiceClient,
taskMaster,
serviceAnnouncer,
self,
Maps.<String, LoadQueuePeon>newConcurrentMap()
);
}
DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
DruidNode self,
ConcurrentMap<String, LoadQueuePeon> loadQueuePeonMap
)
{
this.config = config;
this.zkPaths = zkPaths;
this.configManager = configManager;
this.databaseSegmentManager = databaseSegmentManager;
this.serverInventoryView = serverInventoryView;
this.databaseRuleManager = databaseRuleManager;
this.curator = curator;
this.emitter = emitter;
this.indexingServiceClient = indexingServiceClient;
this.taskMaster = taskMaster;
this.serviceAnnouncer = serviceAnnouncer;
this.self = self;
this.exec = scheduledExecutorFactory.create(1, "Coordinator-Exec--%d");
this.leaderLatch = new AtomicReference<>(null);
this.loadManagementPeons = loadQueuePeonMap;
}
public boolean isLeader()
{
return leader;
}
public Map<String, LoadQueuePeon> getLoadManagementPeons()
{
return loadManagementPeons;
}
public Map<String, CountingMap<String>> getReplicationStatus()
{
final Map<String, CountingMap<String>> retVal = Maps.newHashMap();
if (segmentReplicantLookup == null) {
return retVal;
}
final DateTime now = new DateTime();
for (DataSegment segment : getAvailableDataSegments()) {
List<Rule> rules = databaseRuleManager.getRulesWithDefault(segment.getDataSource());
for (Rule rule : rules) {
if (rule instanceof LoadRule && rule.appliesTo(segment, now)) {
for (Map.Entry<String, Integer> entry : ((LoadRule) rule).getTieredReplicants().entrySet()) {
CountingMap<String> dataSourceMap = retVal.get(entry.getKey());
if (dataSourceMap == null) {
dataSourceMap = new CountingMap<>();
retVal.put(entry.getKey(), dataSourceMap);
}
int diff = Math.max(
entry.getValue() - segmentReplicantLookup.getTotalReplicants(segment.getIdentifier(), entry.getKey()),
0
);
dataSourceMap.add(segment.getDataSource(), diff);
}
break;
}
}
}
return retVal;
}
public CountingMap<String> getSegmentAvailability()
{
final CountingMap<String> retVal = new CountingMap<>();
if (segmentReplicantLookup == null) {
return retVal;
}
for (DataSegment segment : getAvailableDataSegments()) {
int available = (segmentReplicantLookup.getTotalReplicants(segment.getIdentifier()) == 0) ? 0 : 1;
retVal.add(segment.getDataSource(), 1 - available);
}
return retVal;
}
public Map<String, Double> getLoadStatus()
{
// find available segments
Map<String, Set<DataSegment>> availableSegments = Maps.newHashMap();
for (DataSegment dataSegment : getAvailableDataSegments()) {
Set<DataSegment> segments = availableSegments.get(dataSegment.getDataSource());
if (segments == null) {
segments = Sets.newHashSet();
availableSegments.put(dataSegment.getDataSource(), segments);
}
segments.add(dataSegment);
}
// find segments currently loaded
Map<String, Set<DataSegment>> segmentsInCluster = Maps.newHashMap();
for (DruidServer druidServer : serverInventoryView.getInventory()) {
for (DruidDataSource druidDataSource : druidServer.getDataSources()) {
Set<DataSegment> segments = segmentsInCluster.get(druidDataSource.getName());
if (segments == null) {
segments = Sets.newHashSet();
segmentsInCluster.put(druidDataSource.getName(), segments);
}
segments.addAll(druidDataSource.getSegments());
}
}
// compare available segments with currently loaded
Map<String, Double> loadStatus = Maps.newHashMap();
for (Map.Entry<String, Set<DataSegment>> entry : availableSegments.entrySet()) {
String dataSource = entry.getKey();
Set<DataSegment> segmentsAvailable = entry.getValue();
Set<DataSegment> loadedSegments = segmentsInCluster.get(dataSource);
if (loadedSegments == null) {
loadedSegments = Sets.newHashSet();
}
Set<DataSegment> unloadedSegments = Sets.difference(segmentsAvailable, loadedSegments);
loadStatus.put(
dataSource,
100 * ((double) (segmentsAvailable.size() - unloadedSegments.size()) / (double) segmentsAvailable.size())
);
}
return loadStatus;
}
public CoordinatorDynamicConfig getDynamicConfigs()
{
return configManager.watch(
CoordinatorDynamicConfig.CONFIG_KEY,
CoordinatorDynamicConfig.class,
new CoordinatorDynamicConfig.Builder().build()
).get();
}
public void removeSegment(DataSegment segment)
{
log.info("Removing Segment[%s]", segment);
databaseSegmentManager.removeSegment(segment.getDataSource(), segment.getIdentifier());
}
public void removeDatasource(String ds)
{
databaseSegmentManager.removeDatasource(ds);
}
public void enableDatasource(String ds)
{
databaseSegmentManager.enableDatasource(ds);
}
public String getCurrentLeader()
{
try {
final LeaderLatch latch = leaderLatch.get();
if (latch == null) {
return null;
}
Participant participant = latch.getLeader();
if (participant.isLeader()) {
return participant.getId();
}
return null;
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void moveSegment(
ImmutableDruidServer fromServer,
ImmutableDruidServer toServer,
String segmentName,
final LoadPeonCallback callback
)
{
try {
if (fromServer.getMetadata().equals(toServer.getMetadata())) {
throw new IAE("Cannot move [%s] to and from the same server [%s]", segmentName, fromServer.getName());
}
final DataSegment segment = fromServer.getSegment(segmentName);
if (segment == null) {
throw new IAE("Unable to find segment [%s] on server [%s]", segmentName, fromServer.getName());
}
final LoadQueuePeon loadPeon = loadManagementPeons.get(toServer.getName());
if (loadPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", toServer.getName());
}
final LoadQueuePeon dropPeon = loadManagementPeons.get(fromServer.getName());
if (dropPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", fromServer.getName());
}
final ServerHolder toHolder = new ServerHolder(toServer, loadPeon);
if (toHolder.getAvailableSize() < segment.getSize()) {
throw new IAE(
"Not enough capacity on server [%s] for segment [%s]. Required: %,d, available: %,d.",
toServer.getName(),
segment,
segment.getSize(),
toHolder.getAvailableSize()
);
}
final String toLoadQueueSegPath = ZKPaths.makePath(
ZKPaths.makePath(
zkPaths.getLoadQueuePath(),
toServer.getName()
), segmentName
);
final String toServedSegPath = ZKPaths.makePath(
ZKPaths.makePath(serverInventoryView.getInventoryManagerConfig().getInventoryPath(), toServer.getName()),
segmentName
);
loadPeon.loadSegment(
segment,
new LoadPeonCallback()
{
@Override
public void execute()
{
try {
if (curator.checkExists().forPath(toServedSegPath) != null &&
curator.checkExists().forPath(toLoadQueueSegPath) == null &&
!dropPeon.getSegmentsToDrop().contains(segment)) {
dropPeon.dropSegment(segment, callback);
} else if (callback != null) {
callback.execute();
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
);
}
catch (Exception e) {
log.makeAlert(e, "Exception moving segment %s", segmentName).emit();
if (callback != null) {
callback.execute();
}
}
}
public Set<DataSegment> getOrderedAvailableDataSegments()
{
Set<DataSegment> availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator()));
Iterable<DataSegment> dataSegments = getAvailableDataSegments();
for (DataSegment dataSegment : dataSegments) {
if (dataSegment.getSize() < 0) {
log.makeAlert("No size on Segment, wtf?")
.addData("segment", dataSegment)
.emit();
}
availableSegments.add(dataSegment);
}
return availableSegments;
}
public Iterable<DataSegment> getAvailableDataSegments()
{
return Iterables.concat(
Iterables.transform(
databaseSegmentManager.getInventory(),
new Function<DruidDataSource, Iterable<DataSegment>>()
{
@Override
public Iterable<DataSegment> apply(DruidDataSource input)
{
return input.getSegments();
}
}
)
);
}
@LifecycleStart
public void start()
{
synchronized (lock) {
if (started) {
return;
}
started = true;
createNewLeaderLatch();
try {
leaderLatch.get().start();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
private LeaderLatch createNewLeaderLatch()
{
final LeaderLatch newLeaderLatch = new LeaderLatch(
curator, ZKPaths.makePath(zkPaths.getCoordinatorPath(), COORDINATOR_OWNER_NODE), config.getHost()
);
newLeaderLatch.addListener(
new LeaderLatchListener()
{
@Override
public void isLeader()
{
DruidCoordinator.this.becomeLeader();
}
@Override
public void notLeader()
{
DruidCoordinator.this.stopBeingLeader();
}
},
Execs.singleThreaded("CoordinatorLeader-%s")
);
return leaderLatch.getAndSet(newLeaderLatch);
}
@LifecycleStop
public void stop()
{
synchronized (lock) {
if (!started) {
return;
}
stopBeingLeader();
try {
leaderLatch.get().close();
}
catch (IOException e) {
log.warn(e, "Unable to close leaderLatch, ignoring");
}
started = false;
exec.shutdownNow();
}
}
private void becomeLeader()
{
synchronized (lock) {
if (!started) {
return;
}
log.info("I am the leader of the coordinators, all must bow!");
try {
leaderCounter++;
leader = true;
databaseSegmentManager.start();
databaseRuleManager.start();
serverInventoryView.start();
serviceAnnouncer.announce(self);
final int startingLeaderCounter = leaderCounter;
final List<Pair<? extends CoordinatorRunnable, Duration>> coordinatorRunnables = Lists.newArrayList();
coordinatorRunnables.add(
Pair.of(
new CoordinatorHistoricalManagerRunnable(startingLeaderCounter),
config.getCoordinatorPeriod()
)
);
if (indexingServiceClient != null) {
coordinatorRunnables.add(
Pair.of(
new CoordinatorIndexingServiceRunnable(
makeIndexingServiceHelpers(
configManager.watch(
DatasourceWhitelist.CONFIG_KEY,
DatasourceWhitelist.class
)
),
startingLeaderCounter
),
config.getCoordinatorIndexingPeriod()
)
);
}
for (final Pair<? extends CoordinatorRunnable, Duration> coordinatorRunnable : coordinatorRunnables) {
ScheduledExecutors.scheduleWithFixedDelay(
exec,
config.getCoordinatorStartDelay(),
coordinatorRunnable.rhs,
new Callable<ScheduledExecutors.Signal>()
{
private final CoordinatorRunnable theRunnable = coordinatorRunnable.lhs;
@Override
public ScheduledExecutors.Signal call()
{
if (leader && startingLeaderCounter == leaderCounter) {
theRunnable.run();
}
if (leader && startingLeaderCounter == leaderCounter) { // (We might no longer be leader)
return ScheduledExecutors.Signal.REPEAT;
} else {
return ScheduledExecutors.Signal.STOP;
}
}
}
);
}
}
catch (Exception e) {
log.makeAlert(e, "Unable to become leader")
.emit();
final LeaderLatch oldLatch = createNewLeaderLatch();
Closeables.closeQuietly(oldLatch);
try {
leaderLatch.get().start();
}
catch (Exception e1) {
// If an exception gets thrown out here, then the coordinator will zombie out 'cause it won't be looking for
// the latch anymore. I don't believe it's actually possible for an Exception to throw out here, but
// Curator likes to have "throws Exception" on methods so it might happen...
log.makeAlert(e1, "I am a zombie")
.emit();
}
}
}
}
private void stopBeingLeader()
{
synchronized (lock) {
try {
leaderCounter++;
log.info("I am no longer the leader...");
for (String server : loadManagementPeons.keySet()) {
LoadQueuePeon peon = loadManagementPeons.remove(server);
peon.stop();
}
loadManagementPeons.clear();
serviceAnnouncer.unannounce(self);
serverInventoryView.stop();
databaseRuleManager.stop();
databaseSegmentManager.stop();
leader = false;
}
catch (Exception e) {
log.makeAlert(e, "Unable to stopBeingLeader").emit();
}
}
}
private List<DruidCoordinatorHelper> makeIndexingServiceHelpers(final AtomicReference<DatasourceWhitelist> whitelistRef)
{
List<DruidCoordinatorHelper> helpers = Lists.newArrayList();
helpers.add(new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this));
if (config.isConvertSegments()) {
helpers.add(new DruidCoordinatorVersionConverter(indexingServiceClient, whitelistRef));
}
if (config.isMergeSegments()) {
helpers.add(new DruidCoordinatorSegmentMerger(indexingServiceClient, whitelistRef));
helpers.add(
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
CoordinatorStats stats = params.getCoordinatorStats();
log.info("Issued merge requests for %s segments", stats.getGlobalStats().get("mergedCount").get());
params.getEmitter().emit(
new ServiceMetricEvent.Builder().build(
"coordinator/merge/count", stats.getGlobalStats().get("mergedCount")
)
);
return params;
}
}
);
}
return ImmutableList.copyOf(helpers);
}
public static class DruidCoordinatorVersionConverter implements DruidCoordinatorHelper
{
private final IndexingServiceClient indexingServiceClient;
private final AtomicReference<DatasourceWhitelist> whitelistRef;
public DruidCoordinatorVersionConverter(
IndexingServiceClient indexingServiceClient,
AtomicReference<DatasourceWhitelist> whitelistRef
)
{
this.indexingServiceClient = indexingServiceClient;
this.whitelistRef = whitelistRef;
}
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
DatasourceWhitelist whitelist = whitelistRef.get();
for (DataSegment dataSegment : params.getAvailableSegments()) {
if (whitelist == null || whitelist.contains(dataSegment.getDataSource())) {
final Integer binaryVersion = dataSegment.getBinaryVersion();
if (binaryVersion == null || binaryVersion < IndexIO.CURRENT_VERSION_ID) {
log.info("Upgrading version on segment[%s]", dataSegment.getIdentifier());
indexingServiceClient.upgradeSegment(dataSegment);
}
}
}
return params;
}
}
public abstract class CoordinatorRunnable implements Runnable
{
private final long startTime = System.currentTimeMillis();
private final List<DruidCoordinatorHelper> helpers;
private final int startingLeaderCounter;
protected CoordinatorRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
this.helpers = helpers;
this.startingLeaderCounter = startingLeaderCounter;
}
@Override
public void run()
{
try {
synchronized (lock) {
final LeaderLatch latch = leaderLatch.get();
if (latch == null || !latch.hasLeadership()) {
log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId());
stopBeingLeader();
return;
}
}
List<Boolean> allStarted = Arrays.asList(
databaseSegmentManager.isStarted(),
serverInventoryView.isStarted()
);
for (Boolean aBoolean : allStarted) {
if (!aBoolean) {
log.error("InventoryManagers not started[%s]", allStarted);
stopBeingLeader();
return;
}
}
BalancerStrategyFactory factory =
new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads());
// Do coordinator stuff.
DruidCoordinatorRuntimeParams params =
DruidCoordinatorRuntimeParams.newBuilder()
.withStartTime(startTime)
.withDatasources(databaseSegmentManager.getInventory())
.withDynamicConfigs(getDynamicConfigs())
.withEmitter(emitter)
.withBalancerStrategyFactory(factory)
.build();
for (DruidCoordinatorHelper helper : helpers) {
// Don't read state and run state in the same helper otherwise racy conditions may exist
if (leader && startingLeaderCounter == leaderCounter) {
params = helper.run(params);
}
}
}
catch (Exception e) {
log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit();
}
}
}
private class CoordinatorHistoricalManagerRunnable extends CoordinatorRunnable
{
public CoordinatorHistoricalManagerRunnable(final int startingLeaderCounter)
{
super(
ImmutableList.of(
new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this),
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
// Display info about all historical servers
Iterable<ImmutableDruidServer> servers = FunctionalIterable
.create(serverInventoryView.getInventory())
.filter(
new Predicate<DruidServer>()
{
@Override
public boolean apply(
DruidServer input
)
{
return input.isAssignable();
}
}
).transform(
new Function<DruidServer, ImmutableDruidServer>()
{
@Override
public ImmutableDruidServer apply(DruidServer input)
{
return input.toImmutableDruidServer();
}
}
);
if (log.isDebugEnabled()) {
log.debug("Servers");
for (ImmutableDruidServer druidServer : servers) {
log.debug(" %s", druidServer);
log.debug(" -- DataSources");
for (ImmutableDruidDataSource druidDataSource : druidServer.getDataSources()) {
log.debug(" %s", druidDataSource);
}
}
}
// Find all historical servers, group them by subType and sort by ascending usage
final DruidCluster cluster = new DruidCluster();
for (ImmutableDruidServer server : servers) {
if (!loadManagementPeons.containsKey(server.getName())) {
String basePath = ZKPaths.makePath(zkPaths.getLoadQueuePath(), server.getName());
LoadQueuePeon loadQueuePeon = taskMaster.giveMePeon(basePath);
log.info("Creating LoadQueuePeon for server[%s] at path[%s]", server.getName(), basePath);
loadManagementPeons.put(server.getName(), loadQueuePeon);
}
cluster.add(new ServerHolder(server, loadManagementPeons.get(server.getName())));
}
segmentReplicantLookup = SegmentReplicantLookup.make(cluster);
// Stop peons for servers that aren't there anymore.
final Set<String> disappeared = Sets.newHashSet(loadManagementPeons.keySet());
for (ImmutableDruidServer server : servers) {
disappeared.remove(server.getName());
}
for (String name : disappeared) {
log.info("Removing listener for server[%s] which is no longer there.", name);
LoadQueuePeon peon = loadManagementPeons.remove(name);
peon.stop();
}
return params.buildFromExisting()
.withDruidCluster(cluster)
.withDatabaseRuleManager(databaseRuleManager)
.withLoadManagementPeons(loadManagementPeons)
.withSegmentReplicantLookup(segmentReplicantLookup)
.withBalancerReferenceTimestamp(DateTime.now())
.build();
}
},
new DruidCoordinatorRuleRunner(DruidCoordinator.this),
new DruidCoordinatorCleanup(DruidCoordinator.this),
new DruidCoordinatorBalancer(DruidCoordinator.this),
new DruidCoordinatorLogger()
),
startingLeaderCounter
);
}
}
private class CoordinatorIndexingServiceRunnable extends CoordinatorRunnable
{
public CoordinatorIndexingServiceRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
super(helpers, startingLeaderCounter);
}
}
}
| server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java | /*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.server.coordinator;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.inject.Inject;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.concurrent.ScheduledExecutorFactory;
import com.metamx.common.concurrent.ScheduledExecutors;
import com.metamx.common.guava.Comparators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.client.DruidDataSource;
import io.druid.client.DruidServer;
import io.druid.client.ImmutableDruidDataSource;
import io.druid.client.ImmutableDruidServer;
import io.druid.client.ServerInventoryView;
import io.druid.client.indexing.IndexingServiceClient;
import io.druid.collections.CountingMap;
import io.druid.common.config.JacksonConfigManager;
import io.druid.concurrent.Execs;
import io.druid.curator.discovery.ServiceAnnouncer;
import io.druid.db.DatabaseRuleManager;
import io.druid.db.DatabaseSegmentManager;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Self;
import io.druid.segment.IndexIO;
import io.druid.server.DruidNode;
import io.druid.server.coordinator.helper.DruidCoordinatorBalancer;
import io.druid.server.coordinator.helper.DruidCoordinatorCleanup;
import io.druid.server.coordinator.helper.DruidCoordinatorHelper;
import io.druid.server.coordinator.helper.DruidCoordinatorLogger;
import io.druid.server.coordinator.helper.DruidCoordinatorRuleRunner;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentInfoLoader;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentMerger;
import io.druid.server.coordinator.rules.LoadRule;
import io.druid.server.coordinator.rules.Rule;
import io.druid.server.initialization.ZkPathsConfig;
import io.druid.timeline.DataSegment;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.Participant;
import org.apache.curator.utils.ZKPaths;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
/**
*/
@ManageLifecycle
public class DruidCoordinator
{
public static final String COORDINATOR_OWNER_NODE = "_COORDINATOR";
private static final EmittingLogger log = new EmittingLogger(DruidCoordinator.class);
private final Object lock = new Object();
private final DruidCoordinatorConfig config;
private final ZkPathsConfig zkPaths;
private final JacksonConfigManager configManager;
private final DatabaseSegmentManager databaseSegmentManager;
private final ServerInventoryView<Object> serverInventoryView;
private final DatabaseRuleManager databaseRuleManager;
private final CuratorFramework curator;
private final ServiceEmitter emitter;
private final IndexingServiceClient indexingServiceClient;
private final ScheduledExecutorService exec;
private final LoadQueueTaskMaster taskMaster;
private final Map<String, LoadQueuePeon> loadManagementPeons;
private final AtomicReference<LeaderLatch> leaderLatch;
private final ServiceAnnouncer serviceAnnouncer;
private final DruidNode self;
private volatile boolean started = false;
private volatile int leaderCounter = 0;
private volatile boolean leader = false;
private volatile SegmentReplicantLookup segmentReplicantLookup = null;
@Inject
public DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
@Self DruidNode self
)
{
this(
config,
zkPaths,
configManager,
databaseSegmentManager,
serverInventoryView,
databaseRuleManager,
curator,
emitter,
scheduledExecutorFactory,
indexingServiceClient,
taskMaster,
serviceAnnouncer,
self,
Maps.<String, LoadQueuePeon>newConcurrentMap()
);
}
DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
DruidNode self,
ConcurrentMap<String, LoadQueuePeon> loadQueuePeonMap
)
{
this.config = config;
this.zkPaths = zkPaths;
this.configManager = configManager;
this.databaseSegmentManager = databaseSegmentManager;
this.serverInventoryView = serverInventoryView;
this.databaseRuleManager = databaseRuleManager;
this.curator = curator;
this.emitter = emitter;
this.indexingServiceClient = indexingServiceClient;
this.taskMaster = taskMaster;
this.serviceAnnouncer = serviceAnnouncer;
this.self = self;
this.exec = scheduledExecutorFactory.create(1, "Coordinator-Exec--%d");
this.leaderLatch = new AtomicReference<>(null);
this.loadManagementPeons = loadQueuePeonMap;
}
public boolean isLeader()
{
return leader;
}
public Map<String, LoadQueuePeon> getLoadManagementPeons()
{
return loadManagementPeons;
}
public Map<String, CountingMap<String>> getReplicationStatus()
{
final Map<String, CountingMap<String>> retVal = Maps.newHashMap();
if (segmentReplicantLookup == null) {
return retVal;
}
final DateTime now = new DateTime();
for (DataSegment segment : getAvailableDataSegments()) {
List<Rule> rules = databaseRuleManager.getRulesWithDefault(segment.getDataSource());
for (Rule rule : rules) {
if (rule instanceof LoadRule && rule.appliesTo(segment, now)) {
for (Map.Entry<String, Integer> entry : ((LoadRule) rule).getTieredReplicants().entrySet()) {
CountingMap<String> dataSourceMap = retVal.get(entry.getKey());
if (dataSourceMap == null) {
dataSourceMap = new CountingMap<>();
retVal.put(entry.getKey(), dataSourceMap);
}
int diff = Math.max(
entry.getValue() - segmentReplicantLookup.getTotalReplicants(segment.getIdentifier(), entry.getKey()),
0
);
dataSourceMap.add(segment.getDataSource(), diff);
}
break;
}
}
}
return retVal;
}
public CountingMap<String> getSegmentAvailability()
{
final CountingMap<String> retVal = new CountingMap<>();
if (segmentReplicantLookup == null) {
return retVal;
}
for (DataSegment segment : getAvailableDataSegments()) {
int available = (segmentReplicantLookup.getTotalReplicants(segment.getIdentifier()) == 0) ? 0 : 1;
retVal.add(segment.getDataSource(), 1 - available);
}
return retVal;
}
public Map<String, Double> getLoadStatus()
{
// find available segments
Map<String, Set<DataSegment>> availableSegments = Maps.newHashMap();
for (DataSegment dataSegment : getAvailableDataSegments()) {
Set<DataSegment> segments = availableSegments.get(dataSegment.getDataSource());
if (segments == null) {
segments = Sets.newHashSet();
availableSegments.put(dataSegment.getDataSource(), segments);
}
segments.add(dataSegment);
}
// find segments currently loaded
Map<String, Set<DataSegment>> segmentsInCluster = Maps.newHashMap();
for (DruidServer druidServer : serverInventoryView.getInventory()) {
for (DruidDataSource druidDataSource : druidServer.getDataSources()) {
Set<DataSegment> segments = segmentsInCluster.get(druidDataSource.getName());
if (segments == null) {
segments = Sets.newHashSet();
segmentsInCluster.put(druidDataSource.getName(), segments);
}
segments.addAll(druidDataSource.getSegments());
}
}
// compare available segments with currently loaded
Map<String, Double> loadStatus = Maps.newHashMap();
for (Map.Entry<String, Set<DataSegment>> entry : availableSegments.entrySet()) {
String dataSource = entry.getKey();
Set<DataSegment> segmentsAvailable = entry.getValue();
Set<DataSegment> loadedSegments = segmentsInCluster.get(dataSource);
if (loadedSegments == null) {
loadedSegments = Sets.newHashSet();
}
Set<DataSegment> unloadedSegments = Sets.difference(segmentsAvailable, loadedSegments);
loadStatus.put(
dataSource,
100 * ((double) (segmentsAvailable.size() - unloadedSegments.size()) / (double) segmentsAvailable.size())
);
}
return loadStatus;
}
public CoordinatorDynamicConfig getDynamicConfigs()
{
return configManager.watch(
CoordinatorDynamicConfig.CONFIG_KEY,
CoordinatorDynamicConfig.class,
new CoordinatorDynamicConfig.Builder().build()
).get();
}
public void removeSegment(DataSegment segment)
{
log.info("Removing Segment[%s]", segment);
databaseSegmentManager.removeSegment(segment.getDataSource(), segment.getIdentifier());
}
public void removeDatasource(String ds)
{
databaseSegmentManager.removeDatasource(ds);
}
public void enableDatasource(String ds)
{
databaseSegmentManager.enableDatasource(ds);
}
public String getCurrentLeader()
{
try {
final LeaderLatch latch = leaderLatch.get();
if (latch == null) {
return null;
}
Participant participant = latch.getLeader();
if (participant.isLeader()) {
return participant.getId();
}
return null;
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void moveSegment(
ImmutableDruidServer fromServer,
ImmutableDruidServer toServer,
String segmentName,
final LoadPeonCallback callback
)
{
try {
if (fromServer.getMetadata().equals(toServer.getMetadata())) {
throw new IAE("Cannot move [%s] to and from the same server [%s]", segmentName, fromServer.getName());
}
final DataSegment segment = fromServer.getSegment(segmentName);
if (segment == null) {
throw new IAE("Unable to find segment [%s] on server [%s]", segmentName, fromServer.getName());
}
final LoadQueuePeon loadPeon = loadManagementPeons.get(toServer.getName());
if (loadPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", toServer.getName());
}
final LoadQueuePeon dropPeon = loadManagementPeons.get(fromServer.getName());
if (dropPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", fromServer.getName());
}
final ServerHolder toHolder = new ServerHolder(toServer, loadPeon);
if (toHolder.getAvailableSize() < segment.getSize()) {
throw new IAE(
"Not enough capacity on server [%s] for segment [%s]. Required: %,d, available: %,d.",
toServer.getName(),
segment,
segment.getSize(),
toHolder.getAvailableSize()
);
}
final String toLoadQueueSegPath = ZKPaths.makePath(
ZKPaths.makePath(
zkPaths.getLoadQueuePath(),
toServer.getName()
), segmentName
);
final String toServedSegPath = ZKPaths.makePath(
ZKPaths.makePath(serverInventoryView.getInventoryManagerConfig().getInventoryPath(), toServer.getName()),
segmentName
);
loadPeon.loadSegment(
segment,
new LoadPeonCallback()
{
@Override
public void execute()
{
try {
if (curator.checkExists().forPath(toServedSegPath) != null &&
curator.checkExists().forPath(toLoadQueueSegPath) == null &&
!dropPeon.getSegmentsToDrop().contains(segment)) {
dropPeon.dropSegment(segment, callback);
} else if (callback != null) {
callback.execute();
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
);
}
catch (Exception e) {
log.makeAlert(e, "Exception moving segment %s", segmentName).emit();
if (callback != null) {
callback.execute();
}
}
}
public Set<DataSegment> getOrderedAvailableDataSegments()
{
Set<DataSegment> availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator()));
Iterable<DataSegment> dataSegments = Iterables.concat(
Iterables.transform(
databaseSegmentManager.getInventory(),
new Function<DruidDataSource, Iterable<DataSegment>>()
{
@Override
public Iterable<DataSegment> apply(DruidDataSource input)
{
return input.getSegments();
}
}
)
);
for (DataSegment dataSegment : dataSegments) {
if (dataSegment.getSize() < 0) {
log.makeAlert("No size on Segment, wtf?")
.addData("segment", dataSegment)
.emit();
}
availableSegments.add(dataSegment);
}
return availableSegments;
}
public Iterable<DataSegment> getAvailableDataSegments()
{
return Iterables.concat(
Iterables.transform(
databaseSegmentManager.getInventory(),
new Function<DruidDataSource, Iterable<DataSegment>>()
{
@Override
public Iterable<DataSegment> apply(DruidDataSource input)
{
return input.getSegments();
}
}
)
);
}
@LifecycleStart
public void start()
{
synchronized (lock) {
if (started) {
return;
}
started = true;
createNewLeaderLatch();
try {
leaderLatch.get().start();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
private LeaderLatch createNewLeaderLatch()
{
final LeaderLatch newLeaderLatch = new LeaderLatch(
curator, ZKPaths.makePath(zkPaths.getCoordinatorPath(), COORDINATOR_OWNER_NODE), config.getHost()
);
newLeaderLatch.addListener(
new LeaderLatchListener()
{
@Override
public void isLeader()
{
DruidCoordinator.this.becomeLeader();
}
@Override
public void notLeader()
{
DruidCoordinator.this.stopBeingLeader();
}
},
Execs.singleThreaded("CoordinatorLeader-%s")
);
return leaderLatch.getAndSet(newLeaderLatch);
}
@LifecycleStop
public void stop()
{
synchronized (lock) {
if (!started) {
return;
}
stopBeingLeader();
try {
leaderLatch.get().close();
}
catch (IOException e) {
log.warn(e, "Unable to close leaderLatch, ignoring");
}
started = false;
exec.shutdownNow();
}
}
private void becomeLeader()
{
synchronized (lock) {
if (!started) {
return;
}
log.info("I am the leader of the coordinators, all must bow!");
try {
leaderCounter++;
leader = true;
databaseSegmentManager.start();
databaseRuleManager.start();
serverInventoryView.start();
serviceAnnouncer.announce(self);
final int startingLeaderCounter = leaderCounter;
final List<Pair<? extends CoordinatorRunnable, Duration>> coordinatorRunnables = Lists.newArrayList();
coordinatorRunnables.add(
Pair.of(
new CoordinatorHistoricalManagerRunnable(startingLeaderCounter),
config.getCoordinatorPeriod()
)
);
if (indexingServiceClient != null) {
coordinatorRunnables.add(
Pair.of(
new CoordinatorIndexingServiceRunnable(
makeIndexingServiceHelpers(
configManager.watch(
DatasourceWhitelist.CONFIG_KEY,
DatasourceWhitelist.class
)
),
startingLeaderCounter
),
config.getCoordinatorIndexingPeriod()
)
);
}
for (final Pair<? extends CoordinatorRunnable, Duration> coordinatorRunnable : coordinatorRunnables) {
ScheduledExecutors.scheduleWithFixedDelay(
exec,
config.getCoordinatorStartDelay(),
coordinatorRunnable.rhs,
new Callable<ScheduledExecutors.Signal>()
{
private final CoordinatorRunnable theRunnable = coordinatorRunnable.lhs;
@Override
public ScheduledExecutors.Signal call()
{
if (leader && startingLeaderCounter == leaderCounter) {
theRunnable.run();
}
if (leader && startingLeaderCounter == leaderCounter) { // (We might no longer be leader)
return ScheduledExecutors.Signal.REPEAT;
} else {
return ScheduledExecutors.Signal.STOP;
}
}
}
);
}
}
catch (Exception e) {
log.makeAlert(e, "Unable to become leader")
.emit();
final LeaderLatch oldLatch = createNewLeaderLatch();
Closeables.closeQuietly(oldLatch);
try {
leaderLatch.get().start();
}
catch (Exception e1) {
// If an exception gets thrown out here, then the coordinator will zombie out 'cause it won't be looking for
// the latch anymore. I don't believe it's actually possible for an Exception to throw out here, but
// Curator likes to have "throws Exception" on methods so it might happen...
log.makeAlert(e1, "I am a zombie")
.emit();
}
}
}
}
private void stopBeingLeader()
{
synchronized (lock) {
try {
leaderCounter++;
log.info("I am no longer the leader...");
for (String server : loadManagementPeons.keySet()) {
LoadQueuePeon peon = loadManagementPeons.remove(server);
peon.stop();
}
loadManagementPeons.clear();
serviceAnnouncer.unannounce(self);
serverInventoryView.stop();
databaseRuleManager.stop();
databaseSegmentManager.stop();
leader = false;
}
catch (Exception e) {
log.makeAlert(e, "Unable to stopBeingLeader").emit();
}
}
}
private List<DruidCoordinatorHelper> makeIndexingServiceHelpers(final AtomicReference<DatasourceWhitelist> whitelistRef)
{
List<DruidCoordinatorHelper> helpers = Lists.newArrayList();
helpers.add(new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this));
if (config.isConvertSegments()) {
helpers.add(new DruidCoordinatorVersionConverter(indexingServiceClient, whitelistRef));
}
if (config.isMergeSegments()) {
helpers.add(new DruidCoordinatorSegmentMerger(indexingServiceClient, whitelistRef));
helpers.add(
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
CoordinatorStats stats = params.getCoordinatorStats();
log.info("Issued merge requests for %s segments", stats.getGlobalStats().get("mergedCount").get());
params.getEmitter().emit(
new ServiceMetricEvent.Builder().build(
"coordinator/merge/count", stats.getGlobalStats().get("mergedCount")
)
);
return params;
}
}
);
}
return ImmutableList.copyOf(helpers);
}
public static class DruidCoordinatorVersionConverter implements DruidCoordinatorHelper
{
private final IndexingServiceClient indexingServiceClient;
private final AtomicReference<DatasourceWhitelist> whitelistRef;
public DruidCoordinatorVersionConverter(
IndexingServiceClient indexingServiceClient,
AtomicReference<DatasourceWhitelist> whitelistRef
)
{
this.indexingServiceClient = indexingServiceClient;
this.whitelistRef = whitelistRef;
}
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
DatasourceWhitelist whitelist = whitelistRef.get();
for (DataSegment dataSegment : params.getAvailableSegments()) {
if (whitelist == null || whitelist.contains(dataSegment.getDataSource())) {
final Integer binaryVersion = dataSegment.getBinaryVersion();
if (binaryVersion == null || binaryVersion < IndexIO.CURRENT_VERSION_ID) {
log.info("Upgrading version on segment[%s]", dataSegment.getIdentifier());
indexingServiceClient.upgradeSegment(dataSegment);
}
}
}
return params;
}
}
public abstract class CoordinatorRunnable implements Runnable
{
private final long startTime = System.currentTimeMillis();
private final List<DruidCoordinatorHelper> helpers;
private final int startingLeaderCounter;
protected CoordinatorRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
this.helpers = helpers;
this.startingLeaderCounter = startingLeaderCounter;
}
@Override
public void run()
{
try {
synchronized (lock) {
final LeaderLatch latch = leaderLatch.get();
if (latch == null || !latch.hasLeadership()) {
log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId());
stopBeingLeader();
return;
}
}
List<Boolean> allStarted = Arrays.asList(
databaseSegmentManager.isStarted(),
serverInventoryView.isStarted()
);
for (Boolean aBoolean : allStarted) {
if (!aBoolean) {
log.error("InventoryManagers not started[%s]", allStarted);
stopBeingLeader();
return;
}
}
BalancerStrategyFactory factory =
new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads());
// Do coordinator stuff.
DruidCoordinatorRuntimeParams params =
DruidCoordinatorRuntimeParams.newBuilder()
.withStartTime(startTime)
.withDatasources(databaseSegmentManager.getInventory())
.withDynamicConfigs(getDynamicConfigs())
.withEmitter(emitter)
.withBalancerStrategyFactory(factory)
.build();
for (DruidCoordinatorHelper helper : helpers) {
// Don't read state and run state in the same helper otherwise racy conditions may exist
if (leader && startingLeaderCounter == leaderCounter) {
params = helper.run(params);
}
}
}
catch (Exception e) {
log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit();
}
}
}
private class CoordinatorHistoricalManagerRunnable extends CoordinatorRunnable
{
public CoordinatorHistoricalManagerRunnable(final int startingLeaderCounter)
{
super(
ImmutableList.of(
new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this),
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
// Display info about all historical servers
Iterable<ImmutableDruidServer> servers = FunctionalIterable
.create(serverInventoryView.getInventory())
.filter(
new Predicate<DruidServer>()
{
@Override
public boolean apply(
DruidServer input
)
{
return input.isAssignable();
}
}
).transform(
new Function<DruidServer, ImmutableDruidServer>()
{
@Override
public ImmutableDruidServer apply(DruidServer input)
{
return input.toImmutableDruidServer();
}
}
);
if (log.isDebugEnabled()) {
log.debug("Servers");
for (ImmutableDruidServer druidServer : servers) {
log.debug(" %s", druidServer);
log.debug(" -- DataSources");
for (ImmutableDruidDataSource druidDataSource : druidServer.getDataSources()) {
log.debug(" %s", druidDataSource);
}
}
}
// Find all historical servers, group them by subType and sort by ascending usage
final DruidCluster cluster = new DruidCluster();
for (ImmutableDruidServer server : servers) {
if (!loadManagementPeons.containsKey(server.getName())) {
String basePath = ZKPaths.makePath(zkPaths.getLoadQueuePath(), server.getName());
LoadQueuePeon loadQueuePeon = taskMaster.giveMePeon(basePath);
log.info("Creating LoadQueuePeon for server[%s] at path[%s]", server.getName(), basePath);
loadManagementPeons.put(server.getName(), loadQueuePeon);
}
cluster.add(new ServerHolder(server, loadManagementPeons.get(server.getName())));
}
segmentReplicantLookup = SegmentReplicantLookup.make(cluster);
// Stop peons for servers that aren't there anymore.
final Set<String> disappeared = Sets.newHashSet(loadManagementPeons.keySet());
for (ImmutableDruidServer server : servers) {
disappeared.remove(server.getName());
}
for (String name : disappeared) {
log.info("Removing listener for server[%s] which is no longer there.", name);
LoadQueuePeon peon = loadManagementPeons.remove(name);
peon.stop();
}
return params.buildFromExisting()
.withDruidCluster(cluster)
.withDatabaseRuleManager(databaseRuleManager)
.withLoadManagementPeons(loadManagementPeons)
.withSegmentReplicantLookup(segmentReplicantLookup)
.withBalancerReferenceTimestamp(DateTime.now())
.build();
}
},
new DruidCoordinatorRuleRunner(DruidCoordinator.this),
new DruidCoordinatorCleanup(DruidCoordinator.this),
new DruidCoordinatorBalancer(DruidCoordinator.this),
new DruidCoordinatorLogger()
),
startingLeaderCounter
);
}
}
private class CoordinatorIndexingServiceRunnable extends CoordinatorRunnable
{
public CoordinatorIndexingServiceRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
super(helpers, startingLeaderCounter);
}
}
}
| remove duplicate code
| server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java | remove duplicate code | <ide><path>erver/src/main/java/io/druid/server/coordinator/DruidCoordinator.java
<ide> {
<ide> Set<DataSegment> availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator()));
<ide>
<del> Iterable<DataSegment> dataSegments = Iterables.concat(
<del> Iterables.transform(
<del> databaseSegmentManager.getInventory(),
<del> new Function<DruidDataSource, Iterable<DataSegment>>()
<del> {
<del> @Override
<del> public Iterable<DataSegment> apply(DruidDataSource input)
<del> {
<del> return input.getSegments();
<del> }
<del> }
<del> )
<del> );
<add> Iterable<DataSegment> dataSegments = getAvailableDataSegments();
<ide>
<ide> for (DataSegment dataSegment : dataSegments) {
<ide> if (dataSegment.getSize() < 0) { |
|
Java | apache-2.0 | 11d7e5d640cbf8b0e8035f196cf355740411e3c2 | 0 | intouchfollowup/dbmaintain,intouchfollowup/dbmaintain | /*
* Copyright DbMaintain.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dbmaintain.database.impl;
import org.dbmaintain.database.Database;
import org.dbmaintain.database.DatabaseConnection;
import org.dbmaintain.database.IdentifierProcessor;
import org.dbmaintain.database.SQLHandler;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of {@link org.dbmaintain.database.Database} for a PostgreSql database.
*
* @author Tim Ducheyne
* @author Sunteya
* @author Filip Neven
*/
public class PostgreSqlDatabase extends Database {
public PostgreSqlDatabase(DatabaseConnection databaseConnection, IdentifierProcessor identifierProcessor) {
super(databaseConnection, identifierProcessor);
}
/**
* @return the database dialect supported by this db support class, not null
*/
@Override
public String getSupportedDatabaseDialect() {
return "postgresql";
}
/**
* Returns the names of all tables in the database.
*
* @return The names of all tables in the database
*/
@Override
public Set<String> getTableNames(String schemaName) {
return getSQLHandler().getItemsAsStringSet("select table_name from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Gets the names of all columns of the given table.
*
* @param tableName The table, not null
* @return The names of the columns of the table with the given name
*/
@Override
public Set<String> getColumnNames(String schemaName, String tableName) {
return getSQLHandler().getItemsAsStringSet("select column_name from information_schema.columns where table_name = '" + tableName + "' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the views in the database schema.
*
* @return The names of all views in the database
*/
@Override
public Set<String> getViewNames(String schemaName) {
return getSQLHandler().getItemsAsStringSet("select table_name from information_schema.tables where table_type = 'VIEW' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the sequences in the database schema.
*
* @return The names of all sequences in the database
*/
@Override
public Set<String> getSequenceNames(String schemaName) {
// Patch from Dan Carleton submitted in forum post
// http://sourceforge.net/forum/forum.php?thread_id=1708520&forum_id=570578
// Should be replaced by the original query on information_schema.sequences in future, since this is a more elegant solution
// This is the original query: getItemsAsStringSet("select sequence_name from information_schema.sequences where sequence_schema = '" + schemaName + "'", getDataSource());
return getSQLHandler().getItemsAsStringSet("select c.relname from pg_class c join pg_namespace n on (c.relnamespace = n.oid) where c.relkind = 'S' and n.nspname = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the triggers in the database schema.
* <p/>
* The drop trigger statement is not compatible with standard SQL in Postgresql.
* You have to do drop trigger 'trigger-name' ON 'table name' instead of drop trigger 'trigger-name'.
* <p/>
* To circumvent this, this method will return the trigger names as follows:
* 'trigger-name' ON 'table name'
*
* @return The names of all triggers in the database, not null
*/
@Override
public Set<String> getTriggerNames(String schemaName) {
Set<String> result = new HashSet<String>();
Set<String> triggerAndTableNames = getSQLHandler().getItemsAsStringSet("select trigger_name || ',' || event_object_table from information_schema.triggers where trigger_schema = '" + schemaName + "'", getDataSource());
for (String triggerAndTableName : triggerAndTableNames) {
String[] parts = triggerAndTableName.split(",");
String triggerName = quoted(parts[0]);
String tableName = qualified(schemaName, parts[1]);
result.add(triggerName + " ON " + tableName);
}
return result;
}
/**
* Drops the sequence with the given name from the database
* Note: the sequence name is surrounded with quotes, making it case-sensitive.
* <p/>
* The method is overriden to handle columns of type serial. For these columns, the sequence should be
* dropped using cascade. Thanks to Peter Oxenham for reporting this issue (UNI-28).
*
* @param sequenceName The sequence to drop (case-sensitive), not null
*/
public void dropSequence(String schemaName, String sequenceName) {
getSQLHandler().execute("drop sequence " + qualified(schemaName, sequenceName) + " cascade", getDataSource());
}
/**
* Drops the trigger with the given name from the database.
* <p/>
* The drop trigger statement is not compatible with standard SQL in Postgresql.
* You have to do drop trigger 'trigger-name' ON 'table name' instead of drop trigger 'trigger-name'.
* <p/>
* To circumvent this, this method expects trigger names as follows:
* 'trigger-name' ON 'table name'
*
* @param triggerName The trigger to drop as 'trigger-name' ON 'table name', not null
*/
@Override
public void dropTrigger(String schemaName, String triggerName) {
getSQLHandler().execute("drop trigger " + triggerName + " cascade", getDataSource());
}
/**
* Removes the table with the given name from the given schema.
* Note: the table name is surrounded with quotes, making it case-sensitive.
*
* @param schemaName The schema, not null
* @param tableName The table to drop (case-sensitive), not null
*/
public void dropTable(String schemaName, String tableName) {
getSQLHandler().execute("drop table if exists " + qualified(schemaName, tableName) + (supportsCascade() ? " cascade" : ""), getDataSource());
}
/**
* Retrieves the names of all user-defined types in the database schema.
*
* @return The names of all types in the database
*/
@Override
public Set<String> getTypeNames(String schemaName) {
String sql =
"SELECT t.typname as type " +
"FROM pg_type t " +
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " +
"WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) " +
"AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid) " +
"AND n.nspname = '" + schemaName + "'";
return getSQLHandler().getItemsAsStringSet(sql, getDataSource());
}
/**
* Disables all referential constraints (e.g. foreign keys) on all table in the schema
*
* @param schemaName The schema, not null
*/
@Override
public void disableReferentialConstraints(String schemaName) {
Set<String> tableNames = getTableNames(schemaName);
for (String tableName : tableNames) {
disableReferentialConstraints(schemaName, tableName);
}
}
// todo refactor (see oracle)
protected void disableReferentialConstraints(String schemaName, String tableName) {
SQLHandler sqlHandler = getSQLHandler();
Set<String> constraintNames = sqlHandler.getItemsAsStringSet("select constraint_name from information_schema.table_constraints con where con.table_name = '" + tableName + "' and constraint_type = 'FOREIGN KEY' and constraint_schema = '" + schemaName + "'", getDataSource());
for (String constraintName : constraintNames) {
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(constraintName), getDataSource());
}
}
/**
* Disables all value constraints (e.g. not null) on all tables in the schema
*
* @param schemaName The schema, not null
*/
@Override
public void disableValueConstraints(String schemaName) {
Set<String> tableNames = getTableNames(schemaName);
for (String tableName : tableNames) {
disableValueConstraints(schemaName, tableName);
}
}
// todo refactor (see oracle)
protected void disableValueConstraints(String schemaName, String tableName) {
SQLHandler sqlHandler = getSQLHandler();
// disable all check and unique constraints
// The join wiht pg_constraints is used to filter out not null check-constraints that are implicitly created by Postgresql
Set<String> constraintNames = sqlHandler.getItemsAsStringSet("select constraint_name from information_schema.table_constraints con, pg_constraint pg_con where pg_con.conname = con.constraint_name and con.table_name = '" + tableName + "' and constraint_type in ('CHECK', 'UNIQUE') and constraint_schema = '" + schemaName + "'", getDataSource());
for (String constraintName : constraintNames) {
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(constraintName), getDataSource());
}
// retrieve the name of the primary key, since we cannot remove the not-null constraint on this column
Set<String> primaryKeyColumnNames = sqlHandler.getItemsAsStringSet("select column_name from information_schema.table_constraints con, information_schema.key_column_usage key where con.table_name = '" + tableName + "' and con.table_schema = '" + schemaName + "' and key.table_name = con.table_name and key.table_schema = con.table_schema and key.constraint_name = con.constraint_name and con.constraint_type = 'PRIMARY KEY'", getDataSource());
// disable all not null constraints
Set<String> notNullColumnNames = sqlHandler.getItemsAsStringSet("select column_name from information_schema.columns where is_nullable = 'NO' and table_name = '" + tableName + "' and table_schema = '" + schemaName + "'", getDataSource());
for (String notNullColumnName : notNullColumnNames) {
if (primaryKeyColumnNames.contains(notNullColumnName)) {
// Do not remove PK constraints
continue;
}
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " alter column " + quoted(notNullColumnName) + " drop not null", getDataSource());
}
}
/**
* Returns the value of the sequence with the given name. <p/> Note: this can have the
* side-effect of increasing the sequence value.
*
* @param sequenceName The sequence, not null
* @return The value of the sequence with the given name
*/
@Override
public long getSequenceValue(String schemaName, String sequenceName) {
return getSQLHandler().getItemAsLong("select last_value from " + qualified(schemaName, sequenceName), getDataSource());
}
/**
* Sets the next value of the sequence with the given sequence name to the given sequence value.
*
* @param sequenceName The sequence, not null
* @param newSequenceValue The value to set
*/
@Override
public void incrementSequenceToValue(String schemaName, String sequenceName, long newSequenceValue) {
getSQLHandler().getItemAsLong("select setval('" + qualified(schemaName, sequenceName) + "', " + newSequenceValue + ")", getDataSource());
}
/**
* Sets the current schema of the database. If a current schema is set, it does not need to be specified
* explicitly in the scripts.
*/
@Override
public void setDatabaseDefaultSchema() {
getSQLHandler().execute("SET search_path TO " + getDefaultSchemaName(), getDataSource());
}
/**
* Sequences are supported.
*
* @return True
*/
@Override
public boolean supportsSequences() {
return true;
}
/**
* Triggers are supported.
*
* @return True
*/
@Override
public boolean supportsTriggers() {
return true;
}
/**
* Types are supported
*
* @return true
*/
@Override
public boolean supportsTypes() {
return true;
}
/**
* Cascade are supported.
*
* @return True
*/
@Override
public boolean supportsCascade() {
return true;
}
/**
* Setting the default schema is supported.
*
* @return True
*/
@Override
public boolean supportsSetDatabaseDefaultSchema() {
return true;
}
}
| dbmaintain/src/main/java/org/dbmaintain/database/impl/PostgreSqlDatabase.java | /*
* Copyright DbMaintain.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dbmaintain.database.impl;
import org.dbmaintain.database.Database;
import org.dbmaintain.database.DatabaseConnection;
import org.dbmaintain.database.IdentifierProcessor;
import org.dbmaintain.database.SQLHandler;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of {@link org.dbmaintain.database.Database} for a PostgreSql database.
*
* @author Tim Ducheyne
* @author Sunteya
* @author Filip Neven
*/
public class PostgreSqlDatabase extends Database {
public PostgreSqlDatabase(DatabaseConnection databaseConnection, IdentifierProcessor identifierProcessor) {
super(databaseConnection, identifierProcessor);
}
/**
* @return the database dialect supported by this db support class, not null
*/
@Override
public String getSupportedDatabaseDialect() {
return "postgresql";
}
/**
* Returns the names of all tables in the database.
*
* @return The names of all tables in the database
*/
@Override
public Set<String> getTableNames(String schemaName) {
return getSQLHandler().getItemsAsStringSet("select table_name from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Gets the names of all columns of the given table.
*
* @param tableName The table, not null
* @return The names of the columns of the table with the given name
*/
@Override
public Set<String> getColumnNames(String schemaName, String tableName) {
return getSQLHandler().getItemsAsStringSet("select column_name from information_schema.columns where table_name = '" + tableName + "' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the views in the database schema.
*
* @return The names of all views in the database
*/
@Override
public Set<String> getViewNames(String schemaName) {
return getSQLHandler().getItemsAsStringSet("select table_name from information_schema.tables where table_type = 'VIEW' and table_schema = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the sequences in the database schema.
*
* @return The names of all sequences in the database
*/
@Override
public Set<String> getSequenceNames(String schemaName) {
// Patch from Dan Carleton submitted in forum post
// http://sourceforge.net/forum/forum.php?thread_id=1708520&forum_id=570578
// Should be replaced by the original query on information_schema.sequences in future, since this is a more elegant solution
// This is the original query: getItemsAsStringSet("select sequence_name from information_schema.sequences where sequence_schema = '" + schemaName + "'", getDataSource());
return getSQLHandler().getItemsAsStringSet("select c.relname from pg_class c join pg_namespace n on (c.relnamespace = n.oid) where c.relkind = 'S' and n.nspname = '" + schemaName + "'", getDataSource());
}
/**
* Retrieves the names of all the triggers in the database schema.
* <p/>
* The drop trigger statement is not compatible with standard SQL in Postgresql.
* You have to do drop trigger 'trigger-name' ON 'table name' instead of drop trigger 'trigger-name'.
* <p/>
* To circumvent this, this method will return the trigger names as follows:
* 'trigger-name' ON 'table name'
*
* @return The names of all triggers in the database, not null
*/
@Override
public Set<String> getTriggerNames(String schemaName) {
Set<String> result = new HashSet<String>();
Set<String> triggerAndTableNames = getSQLHandler().getItemsAsStringSet("select trigger_name || ',' || event_object_table from information_schema.triggers where trigger_schema = '" + schemaName + "'", getDataSource());
for (String triggerAndTableName : triggerAndTableNames) {
String[] parts = triggerAndTableName.split(",");
String triggerName = quoted(parts[0]);
String tableName = qualified(schemaName, parts[1]);
result.add(triggerName + " ON " + tableName);
}
return result;
}
/**
* Drops the sequence with the given name from the database
* Note: the sequence name is surrounded with quotes, making it case-sensitive.
* <p/>
* The method is overriden to handle columns of type serial. For these columns, the sequence should be
* dropped using cascade. Thanks to Peter Oxenham for reporting this issue (UNI-28).
*
* @param sequenceName The sequence to drop (case-sensitive), not null
*/
public void dropSequence(String schemaName, String sequenceName) {
getSQLHandler().execute("drop sequence " + qualified(schemaName, sequenceName) + " cascade", getDataSource());
}
/**
* Drops the trigger with the given name from the database.
* <p/>
* The drop trigger statement is not compatible with standard SQL in Postgresql.
* You have to do drop trigger 'trigger-name' ON 'table name' instead of drop trigger 'trigger-name'.
* <p/>
* To circumvent this, this method expects trigger names as follows:
* 'trigger-name' ON 'table name'
*
* @param triggerName The trigger to drop as 'trigger-name' ON 'table name', not null
*/
@Override
public void dropTrigger(String schemaName, String triggerName) {
getSQLHandler().execute("drop trigger " + triggerName + " cascade", getDataSource());
}
/**
* Retrieves the names of all user-defined types in the database schema.
*
* @return The names of all types in the database
*/
@Override
public Set<String> getTypeNames(String schemaName) {
String sql =
"SELECT t.typname as type " +
"FROM pg_type t " +
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " +
"WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) " +
"AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid) " +
"AND n.nspname = '" + schemaName + "'";
return getSQLHandler().getItemsAsStringSet(sql, getDataSource());
}
/**
* Disables all referential constraints (e.g. foreign keys) on all table in the schema
*
* @param schemaName The schema, not null
*/
@Override
public void disableReferentialConstraints(String schemaName) {
Set<String> tableNames = getTableNames(schemaName);
for (String tableName : tableNames) {
disableReferentialConstraints(schemaName, tableName);
}
}
// todo refactor (see oracle)
protected void disableReferentialConstraints(String schemaName, String tableName) {
SQLHandler sqlHandler = getSQLHandler();
Set<String> constraintNames = sqlHandler.getItemsAsStringSet("select constraint_name from information_schema.table_constraints con where con.table_name = '" + tableName + "' and constraint_type = 'FOREIGN KEY' and constraint_schema = '" + schemaName + "'", getDataSource());
for (String constraintName : constraintNames) {
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(constraintName), getDataSource());
}
}
/**
* Disables all value constraints (e.g. not null) on all tables in the schema
*
* @param schemaName The schema, not null
*/
@Override
public void disableValueConstraints(String schemaName) {
Set<String> tableNames = getTableNames(schemaName);
for (String tableName : tableNames) {
disableValueConstraints(schemaName, tableName);
}
}
// todo refactor (see oracle)
protected void disableValueConstraints(String schemaName, String tableName) {
SQLHandler sqlHandler = getSQLHandler();
// disable all check and unique constraints
// The join wiht pg_constraints is used to filter out not null check-constraints that are implicitly created by Postgresql
Set<String> constraintNames = sqlHandler.getItemsAsStringSet("select constraint_name from information_schema.table_constraints con, pg_constraint pg_con where pg_con.conname = con.constraint_name and con.table_name = '" + tableName + "' and constraint_type in ('CHECK', 'UNIQUE') and constraint_schema = '" + schemaName + "'", getDataSource());
for (String constraintName : constraintNames) {
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(constraintName), getDataSource());
}
// retrieve the name of the primary key, since we cannot remove the not-null constraint on this column
Set<String> primaryKeyColumnNames = sqlHandler.getItemsAsStringSet("select column_name from information_schema.table_constraints con, information_schema.key_column_usage key where con.table_name = '" + tableName + "' and con.table_schema = '" + schemaName + "' and key.table_name = con.table_name and key.table_schema = con.table_schema and key.constraint_name = con.constraint_name and con.constraint_type = 'PRIMARY KEY'", getDataSource());
// disable all not null constraints
Set<String> notNullColumnNames = sqlHandler.getItemsAsStringSet("select column_name from information_schema.columns where is_nullable = 'NO' and table_name = '" + tableName + "' and table_schema = '" + schemaName + "'", getDataSource());
for (String notNullColumnName : notNullColumnNames) {
if (primaryKeyColumnNames.contains(notNullColumnName)) {
// Do not remove PK constraints
continue;
}
sqlHandler.execute("alter table " + qualified(schemaName, tableName) + " alter column " + quoted(notNullColumnName) + " drop not null", getDataSource());
}
}
/**
* Returns the value of the sequence with the given name. <p/> Note: this can have the
* side-effect of increasing the sequence value.
*
* @param sequenceName The sequence, not null
* @return The value of the sequence with the given name
*/
@Override
public long getSequenceValue(String schemaName, String sequenceName) {
return getSQLHandler().getItemAsLong("select last_value from " + qualified(schemaName, sequenceName), getDataSource());
}
/**
* Sets the next value of the sequence with the given sequence name to the given sequence value.
*
* @param sequenceName The sequence, not null
* @param newSequenceValue The value to set
*/
@Override
public void incrementSequenceToValue(String schemaName, String sequenceName, long newSequenceValue) {
getSQLHandler().getItemAsLong("select setval('" + qualified(schemaName, sequenceName) + "', " + newSequenceValue + ")", getDataSource());
}
/**
* Sets the current schema of the database. If a current schema is set, it does not need to be specified
* explicitly in the scripts.
*/
@Override
public void setDatabaseDefaultSchema() {
getSQLHandler().execute("SET search_path TO " + getDefaultSchemaName(), getDataSource());
}
/**
* Sequences are supported.
*
* @return True
*/
@Override
public boolean supportsSequences() {
return true;
}
/**
* Triggers are supported.
*
* @return True
*/
@Override
public boolean supportsTriggers() {
return true;
}
/**
* Types are supported
*
* @return true
*/
@Override
public boolean supportsTypes() {
return true;
}
/**
* Cascade are supported.
*
* @return True
*/
@Override
public boolean supportsCascade() {
return true;
}
/**
* Setting the default schema is supported.
*
* @return True
*/
@Override
public boolean supportsSetDatabaseDefaultSchema() {
return true;
}
}
| DBM-117 - Error dropping partitioned table in Postgres during re-create
| dbmaintain/src/main/java/org/dbmaintain/database/impl/PostgreSqlDatabase.java | DBM-117 - Error dropping partitioned table in Postgres during re-create | <ide><path>bmaintain/src/main/java/org/dbmaintain/database/impl/PostgreSqlDatabase.java
<ide> getSQLHandler().execute("drop trigger " + triggerName + " cascade", getDataSource());
<ide> }
<ide>
<add> /**
<add> * Removes the table with the given name from the given schema.
<add> * Note: the table name is surrounded with quotes, making it case-sensitive.
<add> *
<add> * @param schemaName The schema, not null
<add> * @param tableName The table to drop (case-sensitive), not null
<add> */
<add> public void dropTable(String schemaName, String tableName) {
<add> getSQLHandler().execute("drop table if exists " + qualified(schemaName, tableName) + (supportsCascade() ? " cascade" : ""), getDataSource());
<add> }
<add>
<ide> /**
<ide> * Retrieves the names of all user-defined types in the database schema.
<ide> *
<ide> return getSQLHandler().getItemsAsStringSet(sql, getDataSource());
<ide> }
<ide>
<del>
<ide> /**
<ide> * Disables all referential constraints (e.g. foreign keys) on all table in the schema
<ide> * |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/google/code/morphia/callbacks/TestMultipleCallbackMethods.java' did not match any file(s) known to git
| 26b03f096a7b1ce9a53f0d26f4a1f04f2db7a665 | 1 | crazycode/morphia | package com.google.code.morphia.callbacks;
import junit.framework.Assert;
import org.bson.types.ObjectId;
import org.junit.Test;
import com.google.code.morphia.TestBase;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.PrePersist;
public class TestMultipleCallbackMethods extends TestBase {
static abstract class CallbackAbstractEntity {
@Id
private String _id = new ObjectId().toStringMongod();
public String getId() {
return _id;
}
int foo = 0;
@PrePersist
void prePersist1() {
foo++;
}
@PrePersist
void prePersist2() {
foo++;
}
}
static class SomeEntity extends CallbackAbstractEntity {
}
@Test
public void testMultipleCallbackAnnotation() throws Exception {
SomeEntity entity = new SomeEntity();
ds.save(entity);
Assert.assertEquals(2, entity.foo);
}
} | src/test/java/com/google/code/morphia/callbacks/TestMultipleCallbackMethods.java |
git-svn-id: http://morphia.googlecode.com/svn/trunk/morphia@597 7223e496-fac8-11de-aa3c-59de0406b4f5
| src/test/java/com/google/code/morphia/callbacks/TestMultipleCallbackMethods.java | <ide><path>rc/test/java/com/google/code/morphia/callbacks/TestMultipleCallbackMethods.java
<add>package com.google.code.morphia.callbacks;
<add>
<add>import junit.framework.Assert;
<add>
<add>import org.bson.types.ObjectId;
<add>import org.junit.Test;
<add>
<add>import com.google.code.morphia.TestBase;
<add>import com.google.code.morphia.annotations.Id;
<add>import com.google.code.morphia.annotations.PrePersist;
<add>
<add>public class TestMultipleCallbackMethods extends TestBase {
<add> static abstract class CallbackAbstractEntity {
<add> @Id
<add> private String _id = new ObjectId().toStringMongod();
<add>
<add> public String getId() {
<add> return _id;
<add> }
<add>
<add> int foo = 0;
<add>
<add> @PrePersist
<add> void prePersist1() {
<add> foo++;
<add> }
<add>
<add> @PrePersist
<add> void prePersist2() {
<add> foo++;
<add> }
<add> }
<add>
<add> static class SomeEntity extends CallbackAbstractEntity {
<add>
<add> }
<add>
<add> @Test
<add> public void testMultipleCallbackAnnotation() throws Exception {
<add> SomeEntity entity = new SomeEntity();
<add> ds.save(entity);
<add> Assert.assertEquals(2, entity.foo);
<add> }
<add>} |
||
Java | apache-2.0 | 1af465fa7e326b2957fbc79c0cffd36b555a87fe | 0 | NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime | package com.tns;
public class NativeScriptActivity extends android.app.Activity
{
private final int objectId;
public NativeScriptActivity()
{
com.tns.Platform.initInstance(this);
objectId = com.tns.Platform.getorCreateJavaObjectID(this);
}
public void addContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
{
if (__ho0)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "addContentView", void.class, args);
}
else
{
super.addContentView(param_0, param_1);
}
}
public void applyOverrideConfiguration(android.content.res.Configuration param_0)
{
if (__ho1)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "applyOverrideConfiguration", void.class, args);
}
else
{
super.applyOverrideConfiguration(param_0);
}
}
public boolean bindService(android.content.Intent param_0, android.content.ServiceConnection param_1, int param_2)
{
if (__ho2)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (boolean)com.tns.Platform.callJSMethod(this, "bindService", boolean.class, args);
}
else
{
return super.bindService(param_0, param_1, param_2);
}
}
public int checkCallingOrSelfPermission(java.lang.String param_0)
{
if (__ho3)
{
Object[] args = new Object[1];
args[0] = param_0;
return (int)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfPermission", int.class, args);
}
else
{
return super.checkCallingOrSelfPermission(param_0);
}
}
public int checkCallingOrSelfUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho4)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (int)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfUriPermission", int.class, args);
}
else
{
return super.checkCallingOrSelfUriPermission(param_0, param_1);
}
}
public int checkCallingPermission(java.lang.String param_0)
{
if (__ho5)
{
Object[] args = new Object[1];
args[0] = param_0;
return (int)com.tns.Platform.callJSMethod(this, "checkCallingPermission", int.class, args);
}
else
{
return super.checkCallingPermission(param_0);
}
}
public int checkCallingUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho6)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (int)com.tns.Platform.callJSMethod(this, "checkCallingUriPermission", int.class, args);
}
else
{
return super.checkCallingUriPermission(param_0, param_1);
}
}
public int checkPermission(java.lang.String param_0, int param_1, int param_2)
{
if (__ho7)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (int)com.tns.Platform.callJSMethod(this, "checkPermission", int.class, args);
}
else
{
return super.checkPermission(param_0, param_1, param_2);
}
}
public int checkUriPermission(android.net.Uri param_0, java.lang.String param_1, java.lang.String param_2, int param_3, int param_4, int param_5)
{
if (__ho8)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
return (int)com.tns.Platform.callJSMethod(this, "checkUriPermission", int.class, args);
}
else
{
return super.checkUriPermission(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public int checkUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3)
{
if (__ho8)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (int)com.tns.Platform.callJSMethod(this, "checkUriPermission", int.class, args);
}
else
{
return super.checkUriPermission(param_0, param_1, param_2, param_3);
}
}
public void clearWallpaper() throws java.io.IOException
{
if (__ho9)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "clearWallpaper", void.class, args);
}
else
{
super.clearWallpaper();
}
}
public void closeContextMenu()
{
if (__ho10)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "closeContextMenu", void.class, args);
}
else
{
super.closeContextMenu();
}
}
public void closeOptionsMenu()
{
if (__ho11)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "closeOptionsMenu", void.class, args);
}
else
{
super.closeOptionsMenu();
}
}
public android.content.Context createConfigurationContext(android.content.res.Configuration param_0)
{
if (__ho12)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createConfigurationContext", android.content.Context.class, args);
}
else
{
return super.createConfigurationContext(param_0);
}
}
public android.content.Context createDisplayContext(android.view.Display param_0)
{
if (__ho13)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createDisplayContext", android.content.Context.class, args);
}
else
{
return super.createDisplayContext(param_0);
}
}
public android.content.Context createPackageContext(java.lang.String param_0, int param_1) throws android.content.pm.PackageManager.NameNotFoundException
{
if (__ho14)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createPackageContext", android.content.Context.class, args);
}
else
{
return super.createPackageContext(param_0, param_1);
}
}
public android.app.PendingIntent createPendingResult(int param_0, android.content.Intent param_1, int param_2)
{
if (__ho15)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.app.PendingIntent)com.tns.Platform.callJSMethod(this, "createPendingResult", android.app.PendingIntent.class, args);
}
else
{
return super.createPendingResult(param_0, param_1, param_2);
}
}
public java.lang.String[] databaseList()
{
if (__ho16)
{
Object[] args = null;
return (java.lang.String[])com.tns.Platform.callJSMethod(this, "databaseList", java.lang.String[].class, args);
}
else
{
return super.databaseList();
}
}
public boolean deleteDatabase(java.lang.String param_0)
{
if (__ho17)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "deleteDatabase", boolean.class, args);
}
else
{
return super.deleteDatabase(param_0);
}
}
public boolean deleteFile(java.lang.String param_0)
{
if (__ho18)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "deleteFile", boolean.class, args);
}
else
{
return super.deleteFile(param_0);
}
}
public boolean dispatchGenericMotionEvent(android.view.MotionEvent param_0)
{
if (__ho19)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchGenericMotionEvent", boolean.class, args);
}
else
{
return super.dispatchGenericMotionEvent(param_0);
}
}
public boolean dispatchKeyEvent(android.view.KeyEvent param_0)
{
if (__ho20)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyEvent", boolean.class, args);
}
else
{
return super.dispatchKeyEvent(param_0);
}
}
public boolean dispatchKeyShortcutEvent(android.view.KeyEvent param_0)
{
if (__ho21)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyShortcutEvent", boolean.class, args);
}
else
{
return super.dispatchKeyShortcutEvent(param_0);
}
}
public boolean dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent param_0)
{
if (__ho22)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchPopulateAccessibilityEvent", boolean.class, args);
}
else
{
return super.dispatchPopulateAccessibilityEvent(param_0);
}
}
public boolean dispatchTouchEvent(android.view.MotionEvent param_0)
{
if (__ho23)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchTouchEvent", boolean.class, args);
}
else
{
return super.dispatchTouchEvent(param_0);
}
}
public boolean dispatchTrackballEvent(android.view.MotionEvent param_0)
{
if (__ho24)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "dispatchTrackballEvent", boolean.class, args);
}
else
{
return super.dispatchTrackballEvent(param_0);
}
}
public void dump(java.lang.String param_0, java.io.FileDescriptor param_1, java.io.PrintWriter param_2, java.lang.String[] param_3)
{
if (__ho25)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "dump", void.class, args);
}
else
{
super.dump(param_0, param_1, param_2, param_3);
}
}
public void enforceCallingOrSelfPermission(java.lang.String param_0, java.lang.String param_1)
{
if (__ho26)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfPermission", void.class, args);
}
else
{
super.enforceCallingOrSelfPermission(param_0, param_1);
}
}
public void enforceCallingOrSelfUriPermission(android.net.Uri param_0, int param_1, java.lang.String param_2)
{
if (__ho27)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfUriPermission", void.class, args);
}
else
{
super.enforceCallingOrSelfUriPermission(param_0, param_1, param_2);
}
}
public void enforceCallingPermission(java.lang.String param_0, java.lang.String param_1)
{
if (__ho28)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "enforceCallingPermission", void.class, args);
}
else
{
super.enforceCallingPermission(param_0, param_1);
}
}
public void enforceCallingUriPermission(android.net.Uri param_0, int param_1, java.lang.String param_2)
{
if (__ho29)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "enforceCallingUriPermission", void.class, args);
}
else
{
super.enforceCallingUriPermission(param_0, param_1, param_2);
}
}
public void enforcePermission(java.lang.String param_0, int param_1, int param_2, java.lang.String param_3)
{
if (__ho30)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "enforcePermission", void.class, args);
}
else
{
super.enforcePermission(param_0, param_1, param_2, param_3);
}
}
public void enforceUriPermission(android.net.Uri param_0, java.lang.String param_1, java.lang.String param_2, int param_3, int param_4, int param_5, java.lang.String param_6)
{
if (__ho31)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "enforceUriPermission", void.class, args);
}
else
{
super.enforceUriPermission(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void enforceUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3, java.lang.String param_4)
{
if (__ho31)
{
Object[] args = new Object[5];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
com.tns.Platform.callJSMethod(this, "enforceUriPermission", void.class, args);
}
else
{
super.enforceUriPermission(param_0, param_1, param_2, param_3, param_4);
}
}
public boolean equals(java.lang.Object param_0)
{
if (__ho32)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "equals", boolean.class, args);
}
else
{
return super.equals(param_0);
}
}
public java.lang.String[] fileList()
{
if (__ho33)
{
Object[] args = null;
return (java.lang.String[])com.tns.Platform.callJSMethod(this, "fileList", java.lang.String[].class, args);
}
else
{
return super.fileList();
}
}
public android.view.View findViewById(int param_0)
{
if (__ho34)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.View)com.tns.Platform.callJSMethod(this, "findViewById", android.view.View.class, args);
}
else
{
return super.findViewById(param_0);
}
}
public void finish()
{
if (__ho35)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "finish", void.class, args);
}
else
{
super.finish();
}
}
public void finishActivity(int param_0)
{
if (__ho36)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "finishActivity", void.class, args);
}
else
{
super.finishActivity(param_0);
}
}
public void finishActivityFromChild(android.app.Activity param_0, int param_1)
{
if (__ho37)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "finishActivityFromChild", void.class, args);
}
else
{
super.finishActivityFromChild(param_0, param_1);
}
}
public void finishAffinity()
{
if (__ho38)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "finishAffinity", void.class, args);
}
else
{
super.finishAffinity();
}
}
public void finishFromChild(android.app.Activity param_0)
{
if (__ho39)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "finishFromChild", void.class, args);
}
else
{
super.finishFromChild(param_0);
}
}
public android.app.ActionBar getActionBar()
{
if (__ho40)
{
Object[] args = null;
return (android.app.ActionBar)com.tns.Platform.callJSMethod(this, "getActionBar", android.app.ActionBar.class, args);
}
else
{
return super.getActionBar();
}
}
public android.content.Context getApplicationContext()
{
if (__ho41)
{
Object[] args = null;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "getApplicationContext", android.content.Context.class, args);
}
else
{
return super.getApplicationContext();
}
}
public android.content.pm.ApplicationInfo getApplicationInfo()
{
if (__ho42)
{
Object[] args = null;
return (android.content.pm.ApplicationInfo)com.tns.Platform.callJSMethod(this, "getApplicationInfo", android.content.pm.ApplicationInfo.class, args);
}
else
{
return super.getApplicationInfo();
}
}
public android.content.res.AssetManager getAssets()
{
if (__ho43)
{
Object[] args = null;
return (android.content.res.AssetManager)com.tns.Platform.callJSMethod(this, "getAssets", android.content.res.AssetManager.class, args);
}
else
{
return super.getAssets();
}
}
public android.content.Context getBaseContext()
{
if (__ho44)
{
Object[] args = null;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "getBaseContext", android.content.Context.class, args);
}
else
{
return super.getBaseContext();
}
}
public java.io.File getCacheDir()
{
if (__ho45)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getCacheDir", java.io.File.class, args);
}
else
{
return super.getCacheDir();
}
}
public android.content.ComponentName getCallingActivity()
{
if (__ho46)
{
Object[] args = null;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getCallingActivity", android.content.ComponentName.class, args);
}
else
{
return super.getCallingActivity();
}
}
public java.lang.String getCallingPackage()
{
if (__ho47)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getCallingPackage", java.lang.String.class, args);
}
else
{
return super.getCallingPackage();
}
}
public int getChangingConfigurations()
{
if (__ho48)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "getChangingConfigurations", int.class, args);
}
else
{
return super.getChangingConfigurations();
}
}
public java.lang.ClassLoader getClassLoader()
{
if (__ho49)
{
Object[] args = null;
return (java.lang.ClassLoader)com.tns.Platform.callJSMethod(this, "getClassLoader", java.lang.ClassLoader.class, args);
}
else
{
return super.getClassLoader();
}
}
public android.content.ComponentName getComponentName()
{
if (__ho50)
{
Object[] args = null;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getComponentName", android.content.ComponentName.class, args);
}
else
{
return super.getComponentName();
}
}
public android.content.ContentResolver getContentResolver()
{
if (__ho51)
{
Object[] args = null;
return (android.content.ContentResolver)com.tns.Platform.callJSMethod(this, "getContentResolver", android.content.ContentResolver.class, args);
}
else
{
return super.getContentResolver();
}
}
public android.view.View getCurrentFocus()
{
if (__ho52)
{
Object[] args = null;
return (android.view.View)com.tns.Platform.callJSMethod(this, "getCurrentFocus", android.view.View.class, args);
}
else
{
return super.getCurrentFocus();
}
}
public java.io.File getDatabasePath(java.lang.String param_0)
{
if (__ho53)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getDatabasePath", java.io.File.class, args);
}
else
{
return super.getDatabasePath(param_0);
}
}
public java.io.File getDir(java.lang.String param_0, int param_1)
{
if (__ho54)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getDir", java.io.File.class, args);
}
else
{
return super.getDir(param_0, param_1);
}
}
public java.io.File getExternalCacheDir()
{
if (__ho55)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalCacheDir", java.io.File.class, args);
}
else
{
return super.getExternalCacheDir();
}
}
public java.io.File getExternalFilesDir(java.lang.String param_0)
{
if (__ho56)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalFilesDir", java.io.File.class, args);
}
else
{
return super.getExternalFilesDir(param_0);
}
}
public java.io.File getFileStreamPath(java.lang.String param_0)
{
if (__ho57)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getFileStreamPath", java.io.File.class, args);
}
else
{
return super.getFileStreamPath(param_0);
}
}
public java.io.File getFilesDir()
{
if (__ho58)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getFilesDir", java.io.File.class, args);
}
else
{
return super.getFilesDir();
}
}
public android.app.FragmentManager getFragmentManager()
{
if (__ho59)
{
Object[] args = null;
return (android.app.FragmentManager)com.tns.Platform.callJSMethod(this, "getFragmentManager", android.app.FragmentManager.class, args);
}
else
{
return super.getFragmentManager();
}
}
public android.content.Intent getIntent()
{
if (__ho60)
{
Object[] args = null;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getIntent", android.content.Intent.class, args);
}
else
{
return super.getIntent();
}
}
public java.lang.Object getLastNonConfigurationInstance()
{
if (__ho61)
{
Object[] args = null;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getLastNonConfigurationInstance", java.lang.Object.class, args);
}
else
{
return super.getLastNonConfigurationInstance();
}
}
public android.view.LayoutInflater getLayoutInflater()
{
if (__ho62)
{
Object[] args = null;
return (android.view.LayoutInflater)com.tns.Platform.callJSMethod(this, "getLayoutInflater", android.view.LayoutInflater.class, args);
}
else
{
return super.getLayoutInflater();
}
}
public android.app.LoaderManager getLoaderManager()
{
if (__ho63)
{
Object[] args = null;
return (android.app.LoaderManager)com.tns.Platform.callJSMethod(this, "getLoaderManager", android.app.LoaderManager.class, args);
}
else
{
return super.getLoaderManager();
}
}
public java.lang.String getLocalClassName()
{
if (__ho64)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getLocalClassName", java.lang.String.class, args);
}
else
{
return super.getLocalClassName();
}
}
public android.os.Looper getMainLooper()
{
if (__ho65)
{
Object[] args = null;
return (android.os.Looper)com.tns.Platform.callJSMethod(this, "getMainLooper", android.os.Looper.class, args);
}
else
{
return super.getMainLooper();
}
}
public android.view.MenuInflater getMenuInflater()
{
if (__ho66)
{
Object[] args = null;
return (android.view.MenuInflater)com.tns.Platform.callJSMethod(this, "getMenuInflater", android.view.MenuInflater.class, args);
}
else
{
return super.getMenuInflater();
}
}
public java.io.File getObbDir()
{
if (__ho67)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getObbDir", java.io.File.class, args);
}
else
{
return super.getObbDir();
}
}
public java.lang.String getPackageCodePath()
{
if (__ho68)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageCodePath", java.lang.String.class, args);
}
else
{
return super.getPackageCodePath();
}
}
public android.content.pm.PackageManager getPackageManager()
{
if (__ho69)
{
Object[] args = null;
return (android.content.pm.PackageManager)com.tns.Platform.callJSMethod(this, "getPackageManager", android.content.pm.PackageManager.class, args);
}
else
{
return super.getPackageManager();
}
}
public java.lang.String getPackageName()
{
if (__ho70)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageName", java.lang.String.class, args);
}
else
{
return super.getPackageName();
}
}
public java.lang.String getPackageResourcePath()
{
if (__ho71)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageResourcePath", java.lang.String.class, args);
}
else
{
return super.getPackageResourcePath();
}
}
public android.content.Intent getParentActivityIntent()
{
if (__ho72)
{
Object[] args = null;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getParentActivityIntent", android.content.Intent.class, args);
}
else
{
return super.getParentActivityIntent();
}
}
public android.content.SharedPreferences getPreferences(int param_0)
{
if (__ho73)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getPreferences", android.content.SharedPreferences.class, args);
}
else
{
return super.getPreferences(param_0);
}
}
public int getRequestedOrientation()
{
if (__ho74)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "getRequestedOrientation", int.class, args);
}
else
{
return super.getRequestedOrientation();
}
}
public android.content.res.Resources getResources()
{
if (__ho75)
{
Object[] args = null;
return (android.content.res.Resources)com.tns.Platform.callJSMethod(this, "getResources", android.content.res.Resources.class, args);
}
else
{
return super.getResources();
}
}
public android.content.SharedPreferences getSharedPreferences(java.lang.String param_0, int param_1)
{
if (__ho76)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getSharedPreferences", android.content.SharedPreferences.class, args);
}
else
{
return super.getSharedPreferences(param_0, param_1);
}
}
public java.lang.Object getSystemService(java.lang.String param_0)
{
if (__ho77)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getSystemService", java.lang.Object.class, args);
}
else
{
return super.getSystemService(param_0);
}
}
public int getTaskId()
{
if (__ho78)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "getTaskId", int.class, args);
}
else
{
return super.getTaskId();
}
}
public android.content.res.Resources.Theme getTheme()
{
if (__ho79)
{
Object[] args = null;
return (android.content.res.Resources.Theme)com.tns.Platform.callJSMethod(this, "getTheme", android.content.res.Resources.Theme.class, args);
}
else
{
return super.getTheme();
}
}
public android.graphics.drawable.Drawable getWallpaper()
{
if (__ho80)
{
Object[] args = null;
return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "getWallpaper", android.graphics.drawable.Drawable.class, args);
}
else
{
return super.getWallpaper();
}
}
public int getWallpaperDesiredMinimumHeight()
{
if (__ho81)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumHeight", int.class, args);
}
else
{
return super.getWallpaperDesiredMinimumHeight();
}
}
public int getWallpaperDesiredMinimumWidth()
{
if (__ho82)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumWidth", int.class, args);
}
else
{
return super.getWallpaperDesiredMinimumWidth();
}
}
public android.view.Window getWindow()
{
if (__ho83)
{
Object[] args = null;
return (android.view.Window)com.tns.Platform.callJSMethod(this, "getWindow", android.view.Window.class, args);
}
else
{
return super.getWindow();
}
}
public android.view.WindowManager getWindowManager()
{
if (__ho84)
{
Object[] args = null;
return (android.view.WindowManager)com.tns.Platform.callJSMethod(this, "getWindowManager", android.view.WindowManager.class, args);
}
else
{
return super.getWindowManager();
}
}
public void grantUriPermission(java.lang.String param_0, android.net.Uri param_1, int param_2)
{
if (__ho85)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "grantUriPermission", void.class, args);
}
else
{
super.grantUriPermission(param_0, param_1, param_2);
}
}
public boolean hasWindowFocus()
{
if (__ho86)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "hasWindowFocus", boolean.class, args);
}
else
{
return super.hasWindowFocus();
}
}
public int hashCode()
{
if (__ho87)
{
Object[] args = null;
return (int)com.tns.Platform.callJSMethod(this, "hashCode", int.class, args);
}
else
{
return super.hashCode();
}
}
public void invalidateOptionsMenu()
{
if (__ho88)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "invalidateOptionsMenu", void.class, args);
}
else
{
super.invalidateOptionsMenu();
}
}
public boolean isChangingConfigurations()
{
if (__ho89)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "isChangingConfigurations", boolean.class, args);
}
else
{
return super.isChangingConfigurations();
}
}
public boolean isDestroyed()
{
if (__ho90)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "isDestroyed", boolean.class, args);
}
else
{
return super.isDestroyed();
}
}
public boolean isFinishing()
{
if (__ho91)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "isFinishing", boolean.class, args);
}
else
{
return super.isFinishing();
}
}
public boolean isRestricted()
{
if (__ho92)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "isRestricted", boolean.class, args);
}
else
{
return super.isRestricted();
}
}
public boolean isTaskRoot()
{
if (__ho93)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "isTaskRoot", boolean.class, args);
}
else
{
return super.isTaskRoot();
}
}
public boolean moveTaskToBack(boolean param_0)
{
if (__ho94)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "moveTaskToBack", boolean.class, args);
}
else
{
return super.moveTaskToBack(param_0);
}
}
public boolean navigateUpTo(android.content.Intent param_0)
{
if (__ho95)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "navigateUpTo", boolean.class, args);
}
else
{
return super.navigateUpTo(param_0);
}
}
public boolean navigateUpToFromChild(android.app.Activity param_0, android.content.Intent param_1)
{
if (__ho96)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "navigateUpToFromChild", boolean.class, args);
}
else
{
return super.navigateUpToFromChild(param_0, param_1);
}
}
public void onActionModeFinished(android.view.ActionMode param_0)
{
if (__ho97)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onActionModeFinished", void.class, args);
}
else
{
super.onActionModeFinished(param_0);
}
}
public void onActionModeStarted(android.view.ActionMode param_0)
{
if (__ho98)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onActionModeStarted", void.class, args);
}
else
{
super.onActionModeStarted(param_0);
}
}
protected void onActivityResult(int param_0, int param_1, android.content.Intent param_2)
{
if (__ho99)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onActivityResult", void.class, args);
}
else
{
super.onActivityResult(param_0, param_1, param_2);
}
}
protected void onApplyThemeResource(android.content.res.Resources.Theme param_0, int param_1, boolean param_2)
{
if (__ho100)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onApplyThemeResource", void.class, args);
}
else
{
super.onApplyThemeResource(param_0, param_1, param_2);
}
}
public void onAttachFragment(android.app.Fragment param_0)
{
if (__ho101)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onAttachFragment", void.class, args);
}
else
{
super.onAttachFragment(param_0);
}
}
public void onAttachedToWindow()
{
if (__ho102)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onAttachedToWindow", void.class, args);
}
else
{
super.onAttachedToWindow();
}
}
public void onBackPressed()
{
if (__ho103)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onBackPressed", void.class, args);
}
else
{
super.onBackPressed();
}
}
protected void onChildTitleChanged(android.app.Activity param_0, java.lang.CharSequence param_1)
{
if (__ho104)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onChildTitleChanged", void.class, args);
}
else
{
super.onChildTitleChanged(param_0, param_1);
}
}
public void onConfigurationChanged(android.content.res.Configuration param_0)
{
if (__ho105)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onConfigurationChanged", void.class, args);
}
else
{
super.onConfigurationChanged(param_0);
}
}
public void onContentChanged()
{
if (__ho106)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onContentChanged", void.class, args);
}
else
{
super.onContentChanged();
}
}
public boolean onContextItemSelected(android.view.MenuItem param_0)
{
if (__ho107)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onContextItemSelected", boolean.class, args);
}
else
{
return super.onContextItemSelected(param_0);
}
}
public void onContextMenuClosed(android.view.Menu param_0)
{
if (__ho108)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onContextMenuClosed", void.class, args);
}
else
{
super.onContextMenuClosed(param_0);
}
}
private native String[] getMethodOverrides(int objectId, Object[] packagesArgs);
protected void onCreate(android.os.Bundle param_0)
{
Object[] packagesArgs = Platform.packageArgs(this);
String[] methodOverrides = getMethodOverrides(objectId, packagesArgs);
setMethodOverrides(methodOverrides);
if (__ho109)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onCreate", void.class, args);
android.util.Log.d(com.tns.Platform.DEFAULT_LOG_TAG, "NativeScriptActivity.onCreate called");
}
else
{
super.onCreate(param_0);
}
}
public void onCreateContextMenu(android.view.ContextMenu param_0, android.view.View param_1, android.view.ContextMenu.ContextMenuInfo param_2)
{
if (__ho110)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onCreateContextMenu", void.class, args);
}
else
{
super.onCreateContextMenu(param_0, param_1, param_2);
}
}
public java.lang.CharSequence onCreateDescription()
{
if (__ho111)
{
Object[] args = null;
return (java.lang.CharSequence)com.tns.Platform.callJSMethod(this, "onCreateDescription", java.lang.CharSequence.class, args);
}
else
{
return super.onCreateDescription();
}
}
protected android.app.Dialog onCreateDialog(int param_0, android.os.Bundle param_1)
{
if (__ho112)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", android.app.Dialog.class, args);
}
else
{
return super.onCreateDialog(param_0, param_1);
}
}
protected android.app.Dialog onCreateDialog(int param_0)
{
if (__ho112)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", android.app.Dialog.class, args);
}
else
{
return super.onCreateDialog(param_0);
}
}
public void onCreateNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
{
if (__ho113)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onCreateNavigateUpTaskStack", void.class, args);
}
else
{
super.onCreateNavigateUpTaskStack(param_0);
}
}
public boolean onCreateOptionsMenu(android.view.Menu param_0)
{
if (__ho114)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onCreateOptionsMenu", boolean.class, args);
}
else
{
return super.onCreateOptionsMenu(param_0);
}
}
public boolean onCreatePanelMenu(int param_0, android.view.Menu param_1)
{
if (__ho115)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onCreatePanelMenu", boolean.class, args);
}
else
{
return super.onCreatePanelMenu(param_0, param_1);
}
}
public android.view.View onCreatePanelView(int param_0)
{
if (__ho116)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreatePanelView", android.view.View.class, args);
}
else
{
return super.onCreatePanelView(param_0);
}
}
public boolean onCreateThumbnail(android.graphics.Bitmap param_0, android.graphics.Canvas param_1)
{
if (__ho117)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onCreateThumbnail", boolean.class, args);
}
else
{
return super.onCreateThumbnail(param_0, param_1);
}
}
public android.view.View onCreateView(android.view.View param_0, java.lang.String param_1, android.content.Context param_2, android.util.AttributeSet param_3)
{
if (__ho118)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", android.view.View.class, args);
}
else
{
return super.onCreateView(param_0, param_1, param_2, param_3);
}
}
public android.view.View onCreateView(java.lang.String param_0, android.content.Context param_1, android.util.AttributeSet param_2)
{
if (__ho118)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", android.view.View.class, args);
}
else
{
return super.onCreateView(param_0, param_1, param_2);
}
}
protected void onDestroy()
{
if (__ho119)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onDestroy", void.class, args);
}
else
{
super.onDestroy();
}
// TODO: remove from com.tns.Platform.strongInstances
}
public void onDetachedFromWindow()
{
if (__ho120)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onDetachedFromWindow", void.class, args);
}
else
{
super.onDetachedFromWindow();
}
}
public boolean onGenericMotionEvent(android.view.MotionEvent param_0)
{
if (__ho121)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onGenericMotionEvent", boolean.class, args);
}
else
{
return super.onGenericMotionEvent(param_0);
}
}
public boolean onKeyDown(int param_0, android.view.KeyEvent param_1)
{
if (__ho122)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onKeyDown", boolean.class, args);
}
else
{
return super.onKeyDown(param_0, param_1);
}
}
public boolean onKeyLongPress(int param_0, android.view.KeyEvent param_1)
{
if (__ho123)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onKeyLongPress", boolean.class, args);
}
else
{
return super.onKeyLongPress(param_0, param_1);
}
}
public boolean onKeyMultiple(int param_0, int param_1, android.view.KeyEvent param_2)
{
if (__ho124)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (boolean)com.tns.Platform.callJSMethod(this, "onKeyMultiple", boolean.class, args);
}
else
{
return super.onKeyMultiple(param_0, param_1, param_2);
}
}
public boolean onKeyShortcut(int param_0, android.view.KeyEvent param_1)
{
if (__ho125)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onKeyShortcut", boolean.class, args);
}
else
{
return super.onKeyShortcut(param_0, param_1);
}
}
public boolean onKeyUp(int param_0, android.view.KeyEvent param_1)
{
if (__ho126)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onKeyUp", boolean.class, args);
}
else
{
return super.onKeyUp(param_0, param_1);
}
}
public void onLowMemory()
{
if (__ho127)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onLowMemory", void.class, args);
}
else
{
super.onLowMemory();
}
}
public boolean onMenuItemSelected(int param_0, android.view.MenuItem param_1)
{
if (__ho128)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onMenuItemSelected", boolean.class, args);
}
else
{
return super.onMenuItemSelected(param_0, param_1);
}
}
public boolean onMenuOpened(int param_0, android.view.Menu param_1)
{
if (__ho129)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "onMenuOpened", boolean.class, args);
}
else
{
return super.onMenuOpened(param_0, param_1);
}
}
public boolean onNavigateUp()
{
if (__ho130)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "onNavigateUp", boolean.class, args);
}
else
{
return super.onNavigateUp();
}
}
public boolean onNavigateUpFromChild(android.app.Activity param_0)
{
if (__ho131)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onNavigateUpFromChild", boolean.class, args);
}
else
{
return super.onNavigateUpFromChild(param_0);
}
}
protected void onNewIntent(android.content.Intent param_0)
{
if (__ho132)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onNewIntent", void.class, args);
}
else
{
super.onNewIntent(param_0);
}
}
public boolean onOptionsItemSelected(android.view.MenuItem param_0)
{
if (__ho133)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onOptionsItemSelected", boolean.class, args);
}
else
{
return super.onOptionsItemSelected(param_0);
}
}
public void onOptionsMenuClosed(android.view.Menu param_0)
{
if (__ho134)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onOptionsMenuClosed", void.class, args);
}
else
{
super.onOptionsMenuClosed(param_0);
}
}
public void onPanelClosed(int param_0, android.view.Menu param_1)
{
if (__ho135)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onPanelClosed", void.class, args);
}
else
{
super.onPanelClosed(param_0, param_1);
}
}
protected void onPause()
{
if (__ho136)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onPause", void.class, args);
}
else
{
super.onPause();
}
}
protected void onPostCreate(android.os.Bundle param_0)
{
if (__ho137)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onPostCreate", void.class, args);
}
else
{
super.onPostCreate(param_0);
}
}
protected void onPostResume()
{
if (__ho138)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onPostResume", void.class, args);
}
else
{
super.onPostResume();
}
}
protected void onPrepareDialog(int param_0, android.app.Dialog param_1)
{
if (__ho139)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onPrepareDialog", void.class, args);
}
else
{
super.onPrepareDialog(param_0, param_1);
}
}
protected void onPrepareDialog(int param_0, android.app.Dialog param_1, android.os.Bundle param_2)
{
if (__ho139)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onPrepareDialog", void.class, args);
}
else
{
super.onPrepareDialog(param_0, param_1, param_2);
}
}
public void onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
{
if (__ho140)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onPrepareNavigateUpTaskStack", void.class, args);
}
else
{
super.onPrepareNavigateUpTaskStack(param_0);
}
}
public boolean onPrepareOptionsMenu(android.view.Menu param_0)
{
if (__ho141)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onPrepareOptionsMenu", boolean.class, args);
}
else
{
return super.onPrepareOptionsMenu(param_0);
}
}
public boolean onPreparePanel(int param_0, android.view.View param_1, android.view.Menu param_2)
{
if (__ho142)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (boolean)com.tns.Platform.callJSMethod(this, "onPreparePanel", boolean.class, args);
}
else
{
return super.onPreparePanel(param_0, param_1, param_2);
}
}
protected void onRestart()
{
if (__ho143)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onRestart", void.class, args);
}
else
{
super.onRestart();
}
}
protected void onRestoreInstanceState(android.os.Bundle param_0)
{
if (__ho144)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onRestoreInstanceState", void.class, args);
}
else
{
super.onRestoreInstanceState(param_0);
}
}
protected void onResume()
{
if (__ho145)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onResume", void.class, args);
}
else
{
super.onResume();
}
}
public java.lang.Object onRetainNonConfigurationInstance()
{
if (__ho146)
{
Object[] args = null;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "onRetainNonConfigurationInstance", java.lang.Object.class, args);
}
else
{
return super.onRetainNonConfigurationInstance();
}
}
protected void onSaveInstanceState(android.os.Bundle param_0)
{
if (__ho147)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onSaveInstanceState", void.class, args);
}
else
{
super.onSaveInstanceState(param_0);
}
}
public boolean onSearchRequested()
{
if (__ho148)
{
Object[] args = null;
return (boolean)com.tns.Platform.callJSMethod(this, "onSearchRequested", boolean.class, args);
}
else
{
return super.onSearchRequested();
}
}
protected void onStart()
{
if (__ho149)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onStart", void.class, args);
}
else
{
super.onStart();
}
}
protected void onStop()
{
if (__ho150)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onStop", void.class, args);
}
else
{
super.onStop();
}
}
protected void onTitleChanged(java.lang.CharSequence param_0, int param_1)
{
if (__ho151)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onTitleChanged", void.class, args);
}
else
{
super.onTitleChanged(param_0, param_1);
}
}
public boolean onTouchEvent(android.view.MotionEvent param_0)
{
if (__ho152)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onTouchEvent", boolean.class, args);
}
else
{
return super.onTouchEvent(param_0);
}
}
public boolean onTrackballEvent(android.view.MotionEvent param_0)
{
if (__ho153)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "onTrackballEvent", boolean.class, args);
}
else
{
return super.onTrackballEvent(param_0);
}
}
public void onTrimMemory(int param_0)
{
if (__ho154)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onTrimMemory", void.class, args);
}
else
{
super.onTrimMemory(param_0);
}
}
public void onUserInteraction()
{
if (__ho155)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onUserInteraction", void.class, args);
}
else
{
super.onUserInteraction();
}
}
protected void onUserLeaveHint()
{
if (__ho156)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onUserLeaveHint", void.class, args);
}
else
{
super.onUserLeaveHint();
}
}
public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams param_0)
{
if (__ho157)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onWindowAttributesChanged", void.class, args);
}
else
{
super.onWindowAttributesChanged(param_0);
}
}
public void onWindowFocusChanged(boolean param_0)
{
if (__ho158)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onWindowFocusChanged", void.class, args);
}
else
{
super.onWindowFocusChanged(param_0);
}
}
public android.view.ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback param_0)
{
if (__ho159)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "onWindowStartingActionMode", android.view.ActionMode.class, args);
}
else
{
return super.onWindowStartingActionMode(param_0);
}
}
public void openContextMenu(android.view.View param_0)
{
if (__ho160)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "openContextMenu", void.class, args);
}
else
{
super.openContextMenu(param_0);
}
}
public java.io.FileInputStream openFileInput(java.lang.String param_0) throws java.io.FileNotFoundException
{
if (__ho161)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.FileInputStream)com.tns.Platform.callJSMethod(this, "openFileInput", java.io.FileInputStream.class, args);
}
else
{
return super.openFileInput(param_0);
}
}
public java.io.FileOutputStream openFileOutput(java.lang.String param_0, int param_1) throws java.io.FileNotFoundException
{
if (__ho162)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (java.io.FileOutputStream)com.tns.Platform.callJSMethod(this, "openFileOutput", java.io.FileOutputStream.class, args);
}
else
{
return super.openFileOutput(param_0, param_1);
}
}
public void openOptionsMenu()
{
if (__ho163)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "openOptionsMenu", void.class, args);
}
else
{
super.openOptionsMenu();
}
}
public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2, android.database.DatabaseErrorHandler param_3)
{
if (__ho164)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", android.database.sqlite.SQLiteDatabase.class, args);
}
else
{
return super.openOrCreateDatabase(param_0, param_1, param_2, param_3);
}
}
public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2)
{
if (__ho164)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", android.database.sqlite.SQLiteDatabase.class, args);
}
else
{
return super.openOrCreateDatabase(param_0, param_1, param_2);
}
}
public void overridePendingTransition(int param_0, int param_1)
{
if (__ho165)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "overridePendingTransition", void.class, args);
}
else
{
super.overridePendingTransition(param_0, param_1);
}
}
public android.graphics.drawable.Drawable peekWallpaper()
{
if (__ho166)
{
Object[] args = null;
return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "peekWallpaper", android.graphics.drawable.Drawable.class, args);
}
else
{
return super.peekWallpaper();
}
}
public void recreate()
{
if (__ho167)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "recreate", void.class, args);
}
else
{
super.recreate();
}
}
public void registerComponentCallbacks(android.content.ComponentCallbacks param_0)
{
if (__ho168)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "registerComponentCallbacks", void.class, args);
}
else
{
super.registerComponentCallbacks(param_0);
}
}
public void registerForContextMenu(android.view.View param_0)
{
if (__ho169)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "registerForContextMenu", void.class, args);
}
else
{
super.registerForContextMenu(param_0);
}
}
public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1, java.lang.String param_2, android.os.Handler param_3)
{
if (__ho170)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", android.content.Intent.class, args);
}
else
{
return super.registerReceiver(param_0, param_1, param_2, param_3);
}
}
public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1)
{
if (__ho170)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", android.content.Intent.class, args);
}
else
{
return super.registerReceiver(param_0, param_1);
}
}
public void removeStickyBroadcast(android.content.Intent param_0)
{
if (__ho171)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "removeStickyBroadcast", void.class, args);
}
else
{
super.removeStickyBroadcast(param_0);
}
}
public void removeStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho172)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "removeStickyBroadcastAsUser", void.class, args);
}
else
{
super.removeStickyBroadcastAsUser(param_0, param_1);
}
}
public void revokeUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho173)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "revokeUriPermission", void.class, args);
}
else
{
super.revokeUriPermission(param_0, param_1);
}
}
public void sendBroadcast(android.content.Intent param_0, java.lang.String param_1)
{
if (__ho174)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendBroadcast", void.class, args);
}
else
{
super.sendBroadcast(param_0, param_1);
}
}
public void sendBroadcast(android.content.Intent param_0)
{
if (__ho174)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "sendBroadcast", void.class, args);
}
else
{
super.sendBroadcast(param_0);
}
}
public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2)
{
if (__ho175)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", void.class, args);
}
else
{
super.sendBroadcastAsUser(param_0, param_1, param_2);
}
}
public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho175)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", void.class, args);
}
else
{
super.sendBroadcastAsUser(param_0, param_1);
}
}
public void sendOrderedBroadcast(android.content.Intent param_0, java.lang.String param_1, android.content.BroadcastReceiver param_2, android.os.Handler param_3, int param_4, java.lang.String param_5, android.os.Bundle param_6)
{
if (__ho176)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", void.class, args);
}
else
{
super.sendOrderedBroadcast(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void sendOrderedBroadcast(android.content.Intent param_0, java.lang.String param_1)
{
if (__ho176)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", void.class, args);
}
else
{
super.sendOrderedBroadcast(param_0, param_1);
}
}
public void sendOrderedBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2, android.content.BroadcastReceiver param_3, android.os.Handler param_4, int param_5, java.lang.String param_6, android.os.Bundle param_7)
{
if (__ho177)
{
Object[] args = new Object[8];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
args[7] = param_7;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcastAsUser", void.class, args);
}
else
{
super.sendOrderedBroadcastAsUser(param_0, param_1, param_2, param_3, param_4, param_5, param_6, param_7);
}
}
public void sendStickyBroadcast(android.content.Intent param_0)
{
if (__ho178)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "sendStickyBroadcast", void.class, args);
}
else
{
super.sendStickyBroadcast(param_0);
}
}
public void sendStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho179)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendStickyBroadcastAsUser", void.class, args);
}
else
{
super.sendStickyBroadcastAsUser(param_0, param_1);
}
}
public void sendStickyOrderedBroadcast(android.content.Intent param_0, android.content.BroadcastReceiver param_1, android.os.Handler param_2, int param_3, java.lang.String param_4, android.os.Bundle param_5)
{
if (__ho180)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcast", void.class, args);
}
else
{
super.sendStickyOrderedBroadcast(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void sendStickyOrderedBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, android.content.BroadcastReceiver param_2, android.os.Handler param_3, int param_4, java.lang.String param_5, android.os.Bundle param_6)
{
if (__ho181)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcastAsUser", void.class, args);
}
else
{
super.sendStickyOrderedBroadcastAsUser(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void setContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
{
if (__ho182)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
}
else
{
super.setContentView(param_0, param_1);
}
}
public void setContentView(int param_0)
{
if (__ho182)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
}
else
{
super.setContentView(param_0);
}
}
public void setContentView(android.view.View param_0)
{
if (__ho182)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
}
else
{
super.setContentView(param_0);
}
}
public void setFinishOnTouchOutside(boolean param_0)
{
if (__ho183)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setFinishOnTouchOutside", void.class, args);
}
else
{
super.setFinishOnTouchOutside(param_0);
}
}
public void setIntent(android.content.Intent param_0)
{
if (__ho184)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setIntent", void.class, args);
}
else
{
super.setIntent(param_0);
}
}
public void setRequestedOrientation(int param_0)
{
if (__ho185)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setRequestedOrientation", void.class, args);
}
else
{
super.setRequestedOrientation(param_0);
}
}
public void setTheme(int param_0)
{
if (__ho186)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTheme", void.class, args);
}
else
{
super.setTheme(param_0);
}
}
public void setTitle(int param_0)
{
if (__ho187)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitle", void.class, args);
}
else
{
super.setTitle(param_0);
}
}
public void setTitle(java.lang.CharSequence param_0)
{
if (__ho187)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitle", void.class, args);
}
else
{
super.setTitle(param_0);
}
}
public void setTitleColor(int param_0)
{
if (__ho188)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitleColor", void.class, args);
}
else
{
super.setTitleColor(param_0);
}
}
public void setVisible(boolean param_0)
{
if (__ho189)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setVisible", void.class, args);
}
else
{
super.setVisible(param_0);
}
}
public void setWallpaper(java.io.InputStream param_0) throws java.io.IOException
{
if (__ho190)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setWallpaper", void.class, args);
}
else
{
super.setWallpaper(param_0);
}
}
public void setWallpaper(android.graphics.Bitmap param_0) throws java.io.IOException
{
if (__ho190)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setWallpaper", void.class, args);
}
else
{
super.setWallpaper(param_0);
}
}
public boolean shouldUpRecreateTask(android.content.Intent param_0)
{
if (__ho191)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "shouldUpRecreateTask", boolean.class, args);
}
else
{
return super.shouldUpRecreateTask(param_0);
}
}
public android.view.ActionMode startActionMode(android.view.ActionMode.Callback param_0)
{
if (__ho192)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "startActionMode", android.view.ActionMode.class, args);
}
else
{
return super.startActionMode(param_0);
}
}
public void startActivities(android.content.Intent[] param_0)
{
if (__ho193)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startActivities", void.class, args);
}
else
{
super.startActivities(param_0);
}
}
public void startActivities(android.content.Intent[] param_0, android.os.Bundle param_1)
{
if (__ho193)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivities", void.class, args);
}
else
{
super.startActivities(param_0, param_1);
}
}
public void startActivity(android.content.Intent param_0, android.os.Bundle param_1)
{
if (__ho194)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivity", void.class, args);
}
else
{
super.startActivity(param_0, param_1);
}
}
public void startActivity(android.content.Intent param_0)
{
if (__ho194)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startActivity", void.class, args);
}
else
{
super.startActivity(param_0);
}
}
public void startActivityForResult(android.content.Intent param_0, int param_1)
{
if (__ho195)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivityForResult", void.class, args);
}
else
{
super.startActivityForResult(param_0, param_1);
}
}
public void startActivityForResult(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
{
if (__ho195)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityForResult", void.class, args);
}
else
{
super.startActivityForResult(param_0, param_1, param_2);
}
}
public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2)
{
if (__ho196)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityFromChild", void.class, args);
}
else
{
super.startActivityFromChild(param_0, param_1, param_2);
}
}
public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
{
if (__ho196)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startActivityFromChild", void.class, args);
}
else
{
super.startActivityFromChild(param_0, param_1, param_2, param_3);
}
}
public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2)
{
if (__ho197)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityFromFragment", void.class, args);
}
else
{
super.startActivityFromFragment(param_0, param_1, param_2);
}
}
public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
{
if (__ho197)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startActivityFromFragment", void.class, args);
}
else
{
super.startActivityFromFragment(param_0, param_1, param_2, param_3);
}
}
public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1)
{
if (__ho198)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", boolean.class, args);
}
else
{
return super.startActivityIfNeeded(param_0, param_1);
}
}
public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
{
if (__ho198)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", boolean.class, args);
}
else
{
return super.startActivityIfNeeded(param_0, param_1, param_2);
}
}
public boolean startInstrumentation(android.content.ComponentName param_0, java.lang.String param_1, android.os.Bundle param_2)
{
if (__ho199)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (boolean)com.tns.Platform.callJSMethod(this, "startInstrumentation", boolean.class, args);
}
else
{
return super.startInstrumentation(param_0, param_1, param_2);
}
}
public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4) throws android.content.IntentSender.SendIntentException
{
if (__ho200)
{
Object[] args = new Object[5];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
com.tns.Platform.callJSMethod(this, "startIntentSender", void.class, args);
}
else
{
super.startIntentSender(param_0, param_1, param_2, param_3, param_4);
}
}
public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4, android.os.Bundle param_5) throws android.content.IntentSender.SendIntentException
{
if (__ho200)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "startIntentSender", void.class, args);
}
else
{
super.startIntentSender(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void startIntentSenderForResult(android.content.IntentSender param_0, int param_1, android.content.Intent param_2, int param_3, int param_4, int param_5, android.os.Bundle param_6) throws android.content.IntentSender.SendIntentException
{
if (__ho201)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", void.class, args);
}
else
{
super.startIntentSenderForResult(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void startIntentSenderForResult(android.content.IntentSender param_0, int param_1, android.content.Intent param_2, int param_3, int param_4, int param_5) throws android.content.IntentSender.SendIntentException
{
if (__ho201)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", void.class, args);
}
else
{
super.startIntentSenderForResult(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void startIntentSenderFromChild(android.app.Activity param_0, android.content.IntentSender param_1, int param_2, android.content.Intent param_3, int param_4, int param_5, int param_6, android.os.Bundle param_7) throws android.content.IntentSender.SendIntentException
{
if (__ho202)
{
Object[] args = new Object[8];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
args[7] = param_7;
com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", void.class, args);
}
else
{
super.startIntentSenderFromChild(param_0, param_1, param_2, param_3, param_4, param_5, param_6, param_7);
}
}
public void startIntentSenderFromChild(android.app.Activity param_0, android.content.IntentSender param_1, int param_2, android.content.Intent param_3, int param_4, int param_5, int param_6) throws android.content.IntentSender.SendIntentException
{
if (__ho202)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", void.class, args);
}
else
{
super.startIntentSenderFromChild(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void startManagingCursor(android.database.Cursor param_0)
{
if (__ho203)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startManagingCursor", void.class, args);
}
else
{
super.startManagingCursor(param_0);
}
}
public boolean startNextMatchingActivity(android.content.Intent param_0, android.os.Bundle param_1)
{
if (__ho204)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", boolean.class, args);
}
else
{
return super.startNextMatchingActivity(param_0, param_1);
}
}
public boolean startNextMatchingActivity(android.content.Intent param_0)
{
if (__ho204)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", boolean.class, args);
}
else
{
return super.startNextMatchingActivity(param_0);
}
}
public void startSearch(java.lang.String param_0, boolean param_1, android.os.Bundle param_2, boolean param_3)
{
if (__ho205)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startSearch", void.class, args);
}
else
{
super.startSearch(param_0, param_1, param_2, param_3);
}
}
public android.content.ComponentName startService(android.content.Intent param_0)
{
if (__ho206)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "startService", android.content.ComponentName.class, args);
}
else
{
return super.startService(param_0);
}
}
public void stopManagingCursor(android.database.Cursor param_0)
{
if (__ho207)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "stopManagingCursor", void.class, args);
}
else
{
super.stopManagingCursor(param_0);
}
}
public boolean stopService(android.content.Intent param_0)
{
if (__ho208)
{
Object[] args = new Object[1];
args[0] = param_0;
return (boolean)com.tns.Platform.callJSMethod(this, "stopService", boolean.class, args);
}
else
{
return super.stopService(param_0);
}
}
public void takeKeyEvents(boolean param_0)
{
if (__ho209)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "takeKeyEvents", void.class, args);
}
else
{
super.takeKeyEvents(param_0);
}
}
public java.lang.String toString()
{
if (__ho210)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "toString", java.lang.String.class, args);
}
else
{
return super.toString();
}
}
public void triggerSearch(java.lang.String param_0, android.os.Bundle param_1)
{
if (__ho211)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "triggerSearch", void.class, args);
}
else
{
super.triggerSearch(param_0, param_1);
}
}
public void unbindService(android.content.ServiceConnection param_0)
{
if (__ho212)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unbindService", void.class, args);
}
else
{
super.unbindService(param_0);
}
}
public void unregisterComponentCallbacks(android.content.ComponentCallbacks param_0)
{
if (__ho213)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterComponentCallbacks", void.class, args);
}
else
{
super.unregisterComponentCallbacks(param_0);
}
}
public void unregisterForContextMenu(android.view.View param_0)
{
if (__ho214)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterForContextMenu", void.class, args);
}
else
{
super.unregisterForContextMenu(param_0);
}
}
public void unregisterReceiver(android.content.BroadcastReceiver param_0)
{
if (__ho215)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterReceiver", void.class, args);
}
else
{
super.unregisterReceiver(param_0);
}
}
private void setMethodOverrides(String[] methodOverrides)
{
for (String m: methodOverrides)
{
if (m.equals("onChildTitleChanged")) __ho104= true;
if (m.equals("getChangingConfigurations")) __ho48= true;
if (m.equals("getObbDir")) __ho67= true;
if (m.equals("onSearchRequested")) __ho148= true;
if (m.equals("navigateUpToFromChild")) __ho96= true;
if (m.equals("deleteDatabase")) __ho17= true;
if (m.equals("checkPermission")) __ho7= true;
if (m.equals("enforceUriPermission")) __ho31= true;
if (m.equals("startActivityFromFragment")) __ho197= true;
if (m.equals("databaseList")) __ho16= true;
if (m.equals("dispatchGenericMotionEvent")) __ho19= true;
if (m.equals("getFilesDir")) __ho58= true;
if (m.equals("sendStickyOrderedBroadcastAsUser")) __ho181= true;
if (m.equals("fileList")) __ho33= true;
if (m.equals("getWallpaper")) __ho80= true;
if (m.equals("onBackPressed")) __ho103= true;
if (m.equals("onRestart")) __ho143= true;
if (m.equals("shouldUpRecreateTask")) __ho191= true;
if (m.equals("finishAffinity")) __ho38= true;
if (m.equals("setIntent")) __ho184= true;
if (m.equals("unregisterComponentCallbacks")) __ho213= true;
if (m.equals("dispatchPopulateAccessibilityEvent")) __ho22= true;
if (m.equals("getLoaderManager")) __ho63= true;
if (m.equals("startIntentSender")) __ho200= true;
if (m.equals("openOrCreateDatabase")) __ho164= true;
if (m.equals("getFileStreamPath")) __ho57= true;
if (m.equals("closeOptionsMenu")) __ho11= true;
if (m.equals("getWallpaperDesiredMinimumHeight")) __ho81= true;
if (m.equals("getCallingActivity")) __ho46= true;
if (m.equals("openOptionsMenu")) __ho163= true;
if (m.equals("onWindowAttributesChanged")) __ho157= true;
if (m.equals("invalidateOptionsMenu")) __ho88= true;
if (m.equals("onCreateNavigateUpTaskStack")) __ho113= true;
if (m.equals("removeStickyBroadcast")) __ho171= true;
if (m.equals("dispatchKeyEvent")) __ho20= true;
if (m.equals("getCurrentFocus")) __ho52= true;
if (m.equals("peekWallpaper")) __ho166= true;
if (m.equals("createConfigurationContext")) __ho12= true;
if (m.equals("getApplicationContext")) __ho41= true;
if (m.equals("sendStickyBroadcast")) __ho178= true;
if (m.equals("getResources")) __ho75= true;
if (m.equals("onOptionsMenuClosed")) __ho134= true;
if (m.equals("getSharedPreferences")) __ho76= true;
if (m.equals("setFinishOnTouchOutside")) __ho183= true;
if (m.equals("onAttachedToWindow")) __ho102= true;
if (m.equals("getWallpaperDesiredMinimumWidth")) __ho82= true;
if (m.equals("startInstrumentation")) __ho199= true;
if (m.equals("onPrepareOptionsMenu")) __ho141= true;
if (m.equals("getComponentName")) __ho50= true;
if (m.equals("sendStickyBroadcastAsUser")) __ho179= true;
if (m.equals("setWallpaper")) __ho190= true;
if (m.equals("stopManagingCursor")) __ho207= true;
if (m.equals("getParentActivityIntent")) __ho72= true;
if (m.equals("onTrimMemory")) __ho154= true;
if (m.equals("onActionModeFinished")) __ho97= true;
if (m.equals("recreate")) __ho167= true;
if (m.equals("sendStickyOrderedBroadcast")) __ho180= true;
if (m.equals("onCreateDialog")) __ho112= true;
if (m.equals("startActivityForResult")) __ho195= true;
if (m.equals("onTitleChanged")) __ho151= true;
if (m.equals("getActionBar")) __ho40= true;
if (m.equals("onCreatePanelView")) __ho116= true;
if (m.equals("onNewIntent")) __ho132= true;
if (m.equals("onKeyMultiple")) __ho124= true;
if (m.equals("toString")) __ho210= true;
if (m.equals("applyOverrideConfiguration")) __ho1= true;
if (m.equals("getFragmentManager")) __ho59= true;
if (m.equals("onPanelClosed")) __ho135= true;
if (m.equals("createDisplayContext")) __ho13= true;
if (m.equals("onKeyShortcut")) __ho125= true;
if (m.equals("dispatchTrackballEvent")) __ho24= true;
if (m.equals("addContentView")) __ho0= true;
if (m.equals("onActivityResult")) __ho99= true;
if (m.equals("openFileInput")) __ho161= true;
if (m.equals("getRequestedOrientation")) __ho74= true;
if (m.equals("getWindowManager")) __ho84= true;
if (m.equals("triggerSearch")) __ho211= true;
if (m.equals("finish")) __ho35= true;
if (m.equals("dispatchKeyShortcutEvent")) __ho21= true;
if (m.equals("setVisible")) __ho189= true;
if (m.equals("isDestroyed")) __ho90= true;
if (m.equals("setTitle")) __ho187= true;
if (m.equals("startActivities")) __ho193= true;
if (m.equals("onKeyLongPress")) __ho123= true;
if (m.equals("onGenericMotionEvent")) __ho121= true;
if (m.equals("getMenuInflater")) __ho66= true;
if (m.equals("isChangingConfigurations")) __ho89= true;
if (m.equals("getPackageName")) __ho70= true;
if (m.equals("setRequestedOrientation")) __ho185= true;
if (m.equals("enforceCallingUriPermission")) __ho29= true;
if (m.equals("getLocalClassName")) __ho64= true;
if (m.equals("getWindow")) __ho83= true;
if (m.equals("onRestoreInstanceState")) __ho144= true;
if (m.equals("checkCallingOrSelfUriPermission")) __ho4= true;
if (m.equals("setTitleColor")) __ho188= true;
if (m.equals("getClassLoader")) __ho49= true;
if (m.equals("closeContextMenu")) __ho10= true;
if (m.equals("createPackageContext")) __ho14= true;
if (m.equals("openFileOutput")) __ho162= true;
if (m.equals("moveTaskToBack")) __ho94= true;
if (m.equals("dispatchTouchEvent")) __ho23= true;
if (m.equals("onActionModeStarted")) __ho98= true;
if (m.equals("onPostCreate")) __ho137= true;
if (m.equals("hashCode")) __ho87= true;
if (m.equals("getMainLooper")) __ho65= true;
if (m.equals("getDir")) __ho54= true;
if (m.equals("deleteFile")) __ho18= true;
if (m.equals("getTaskId")) __ho78= true;
if (m.equals("navigateUpTo")) __ho95= true;
if (m.equals("revokeUriPermission")) __ho173= true;
if (m.equals("finishActivity")) __ho36= true;
if (m.equals("finishFromChild")) __ho39= true;
if (m.equals("takeKeyEvents")) __ho209= true;
if (m.equals("overridePendingTransition")) __ho165= true;
if (m.equals("checkCallingPermission")) __ho5= true;
if (m.equals("enforceCallingPermission")) __ho28= true;
if (m.equals("unregisterForContextMenu")) __ho214= true;
if (m.equals("findViewById")) __ho34= true;
if (m.equals("onNavigateUp")) __ho130= true;
if (m.equals("enforceCallingOrSelfPermission")) __ho26= true;
if (m.equals("removeStickyBroadcastAsUser")) __ho172= true;
if (m.equals("onNavigateUpFromChild")) __ho131= true;
if (m.equals("isTaskRoot")) __ho93= true;
if (m.equals("getContentResolver")) __ho51= true;
if (m.equals("getPackageResourcePath")) __ho71= true;
if (m.equals("isFinishing")) __ho91= true;
if (m.equals("getIntent")) __ho60= true;
if (m.equals("onStop")) __ho150= true;
if (m.equals("onWindowStartingActionMode")) __ho159= true;
if (m.equals("enforceCallingOrSelfUriPermission")) __ho27= true;
if (m.equals("getDatabasePath")) __ho53= true;
if (m.equals("startActivityIfNeeded")) __ho198= true;
if (m.equals("getCacheDir")) __ho45= true;
if (m.equals("getTheme")) __ho79= true;
if (m.equals("checkCallingOrSelfPermission")) __ho3= true;
if (m.equals("setTheme")) __ho186= true;
if (m.equals("sendOrderedBroadcastAsUser")) __ho177= true;
if (m.equals("onCreatePanelMenu")) __ho115= true;
if (m.equals("onPostResume")) __ho138= true;
if (m.equals("bindService")) __ho2= true;
if (m.equals("isRestricted")) __ho92= true;
if (m.equals("onPreparePanel")) __ho142= true;
if (m.equals("checkCallingUriPermission")) __ho6= true;
if (m.equals("getSystemService")) __ho77= true;
if (m.equals("startSearch")) __ho205= true;
if (m.equals("getPackageCodePath")) __ho68= true;
if (m.equals("onContextItemSelected")) __ho107= true;
if (m.equals("onApplyThemeResource")) __ho100= true;
if (m.equals("onPause")) __ho136= true;
if (m.equals("finishActivityFromChild")) __ho37= true;
if (m.equals("startActivity")) __ho194= true;
if (m.equals("getLayoutInflater")) __ho62= true;
if (m.equals("startActionMode")) __ho192= true;
if (m.equals("grantUriPermission")) __ho85= true;
if (m.equals("onRetainNonConfigurationInstance")) __ho146= true;
if (m.equals("getAssets")) __ho43= true;
if (m.equals("onDestroy")) __ho119= true;
if (m.equals("onKeyUp")) __ho126= true;
if (m.equals("onMenuOpened")) __ho129= true;
if (m.equals("getExternalFilesDir")) __ho56= true;
if (m.equals("startManagingCursor")) __ho203= true;
if (m.equals("onPrepareDialog")) __ho139= true;
if (m.equals("openContextMenu")) __ho160= true;
if (m.equals("getCallingPackage")) __ho47= true;
if (m.equals("equals")) __ho32= true;
if (m.equals("onAttachFragment")) __ho101= true;
if (m.equals("hasWindowFocus")) __ho86= true;
if (m.equals("onSaveInstanceState")) __ho147= true;
if (m.equals("onCreateOptionsMenu")) __ho114= true;
if (m.equals("registerComponentCallbacks")) __ho168= true;
if (m.equals("sendOrderedBroadcast")) __ho176= true;
if (m.equals("sendBroadcastAsUser")) __ho175= true;
if (m.equals("getExternalCacheDir")) __ho55= true;
if (m.equals("startIntentSenderForResult")) __ho201= true;
if (m.equals("onLowMemory")) __ho127= true;
if (m.equals("onOptionsItemSelected")) __ho133= true;
if (m.equals("onCreateThumbnail")) __ho117= true;
if (m.equals("onStart")) __ho149= true;
if (m.equals("startNextMatchingActivity")) __ho204= true;
if (m.equals("onUserInteraction")) __ho155= true;
if (m.equals("onTrackballEvent")) __ho153= true;
if (m.equals("onTouchEvent")) __ho152= true;
if (m.equals("onUserLeaveHint")) __ho156= true;
if (m.equals("onResume")) __ho145= true;
if (m.equals("getPreferences")) __ho73= true;
if (m.equals("startService")) __ho206= true;
if (m.equals("onContextMenuClosed")) __ho108= true;
if (m.equals("registerReceiver")) __ho170= true;
if (m.equals("getPackageManager")) __ho69= true;
if (m.equals("onCreateView")) __ho118= true;
if (m.equals("onConfigurationChanged")) __ho105= true;
if (m.equals("onContentChanged")) __ho106= true;
if (m.equals("onCreateContextMenu")) __ho110= true;
if (m.equals("onPrepareNavigateUpTaskStack")) __ho140= true;
if (m.equals("getLastNonConfigurationInstance")) __ho61= true;
if (m.equals("onKeyDown")) __ho122= true;
if (m.equals("sendBroadcast")) __ho174= true;
if (m.equals("unbindService")) __ho212= true;
if (m.equals("createPendingResult")) __ho15= true;
if (m.equals("getBaseContext")) __ho44= true;
if (m.equals("registerForContextMenu")) __ho169= true;
if (m.equals("enforcePermission")) __ho30= true;
if (m.equals("checkUriPermission")) __ho8= true;
if (m.equals("dump")) __ho25= true;
if (m.equals("startIntentSenderFromChild")) __ho202= true;
if (m.equals("onCreate")) __ho109= true;
if (m.equals("clearWallpaper")) __ho9= true;
if (m.equals("onWindowFocusChanged")) __ho158= true;
if (m.equals("startActivityFromChild")) __ho196= true;
if (m.equals("onMenuItemSelected")) __ho128= true;
if (m.equals("onCreateDescription")) __ho111= true;
if (m.equals("getApplicationInfo")) __ho42= true;
if (m.equals("setContentView")) __ho182= true;
if (m.equals("unregisterReceiver")) __ho215= true;
if (m.equals("stopService")) __ho208= true;
if (m.equals("onDetachedFromWindow")) __ho120= true;
}
}
private boolean __ho0;
private boolean __ho1;
private boolean __ho2;
private boolean __ho3;
private boolean __ho4;
private boolean __ho5;
private boolean __ho6;
private boolean __ho7;
private boolean __ho8;
private boolean __ho9;
private boolean __ho10;
private boolean __ho11;
private boolean __ho12;
private boolean __ho13;
private boolean __ho14;
private boolean __ho15;
private boolean __ho16;
private boolean __ho17;
private boolean __ho18;
private boolean __ho19;
private boolean __ho20;
private boolean __ho21;
private boolean __ho22;
private boolean __ho23;
private boolean __ho24;
private boolean __ho25;
private boolean __ho26;
private boolean __ho27;
private boolean __ho28;
private boolean __ho29;
private boolean __ho30;
private boolean __ho31;
private boolean __ho32;
private boolean __ho33;
private boolean __ho34;
private boolean __ho35;
private boolean __ho36;
private boolean __ho37;
private boolean __ho38;
private boolean __ho39;
private boolean __ho40;
private boolean __ho41;
private boolean __ho42;
private boolean __ho43;
private boolean __ho44;
private boolean __ho45;
private boolean __ho46;
private boolean __ho47;
private boolean __ho48;
private boolean __ho49;
private boolean __ho50;
private boolean __ho51;
private boolean __ho52;
private boolean __ho53;
private boolean __ho54;
private boolean __ho55;
private boolean __ho56;
private boolean __ho57;
private boolean __ho58;
private boolean __ho59;
private boolean __ho60;
private boolean __ho61;
private boolean __ho62;
private boolean __ho63;
private boolean __ho64;
private boolean __ho65;
private boolean __ho66;
private boolean __ho67;
private boolean __ho68;
private boolean __ho69;
private boolean __ho70;
private boolean __ho71;
private boolean __ho72;
private boolean __ho73;
private boolean __ho74;
private boolean __ho75;
private boolean __ho76;
private boolean __ho77;
private boolean __ho78;
private boolean __ho79;
private boolean __ho80;
private boolean __ho81;
private boolean __ho82;
private boolean __ho83;
private boolean __ho84;
private boolean __ho85;
private boolean __ho86;
private boolean __ho87;
private boolean __ho88;
private boolean __ho89;
private boolean __ho90;
private boolean __ho91;
private boolean __ho92;
private boolean __ho93;
private boolean __ho94;
private boolean __ho95;
private boolean __ho96;
private boolean __ho97;
private boolean __ho98;
private boolean __ho99;
private boolean __ho100;
private boolean __ho101;
private boolean __ho102;
private boolean __ho103;
private boolean __ho104;
private boolean __ho105;
private boolean __ho106;
private boolean __ho107;
private boolean __ho108;
private boolean __ho109;
private boolean __ho110;
private boolean __ho111;
private boolean __ho112;
private boolean __ho113;
private boolean __ho114;
private boolean __ho115;
private boolean __ho116;
private boolean __ho117;
private boolean __ho118;
private boolean __ho119;
private boolean __ho120;
private boolean __ho121;
private boolean __ho122;
private boolean __ho123;
private boolean __ho124;
private boolean __ho125;
private boolean __ho126;
private boolean __ho127;
private boolean __ho128;
private boolean __ho129;
private boolean __ho130;
private boolean __ho131;
private boolean __ho132;
private boolean __ho133;
private boolean __ho134;
private boolean __ho135;
private boolean __ho136;
private boolean __ho137;
private boolean __ho138;
private boolean __ho139;
private boolean __ho140;
private boolean __ho141;
private boolean __ho142;
private boolean __ho143;
private boolean __ho144;
private boolean __ho145;
private boolean __ho146;
private boolean __ho147;
private boolean __ho148;
private boolean __ho149;
private boolean __ho150;
private boolean __ho151;
private boolean __ho152;
private boolean __ho153;
private boolean __ho154;
private boolean __ho155;
private boolean __ho156;
private boolean __ho157;
private boolean __ho158;
private boolean __ho159;
private boolean __ho160;
private boolean __ho161;
private boolean __ho162;
private boolean __ho163;
private boolean __ho164;
private boolean __ho165;
private boolean __ho166;
private boolean __ho167;
private boolean __ho168;
private boolean __ho169;
private boolean __ho170;
private boolean __ho171;
private boolean __ho172;
private boolean __ho173;
private boolean __ho174;
private boolean __ho175;
private boolean __ho176;
private boolean __ho177;
private boolean __ho178;
private boolean __ho179;
private boolean __ho180;
private boolean __ho181;
private boolean __ho182;
private boolean __ho183;
private boolean __ho184;
private boolean __ho185;
private boolean __ho186;
private boolean __ho187;
private boolean __ho188;
private boolean __ho189;
private boolean __ho190;
private boolean __ho191;
private boolean __ho192;
private boolean __ho193;
private boolean __ho194;
private boolean __ho195;
private boolean __ho196;
private boolean __ho197;
private boolean __ho198;
private boolean __ho199;
private boolean __ho200;
private boolean __ho201;
private boolean __ho202;
private boolean __ho203;
private boolean __ho204;
private boolean __ho205;
private boolean __ho206;
private boolean __ho207;
private boolean __ho208;
private boolean __ho209;
private boolean __ho210;
private boolean __ho211;
private boolean __ho212;
private boolean __ho213;
private boolean __ho214;
private boolean __ho215;
}
| src/src/com/tns/NativeScriptActivity.java | package com.tns;
public class NativeScriptActivity extends android.app.Activity
{
private final int objectId;
public NativeScriptActivity()
{
com.tns.Platform.initInstance(this);
objectId = com.tns.Platform.getorCreateJavaObjectID(this);
}
public void addContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
{
if (__ho0)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "addContentView", args);
}
else
{
super.addContentView(param_0, param_1);
}
}
public void applyOverrideConfiguration(android.content.res.Configuration param_0)
{
if (__ho1)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "applyOverrideConfiguration", args);
}
else
{
super.applyOverrideConfiguration(param_0);
}
}
public boolean bindService(android.content.Intent param_0, android.content.ServiceConnection param_1, int param_2)
{
if (__ho2)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Boolean)com.tns.Platform.callJSMethod(this, "bindService", args);
}
else
{
return super.bindService(param_0, param_1, param_2);
}
}
public int checkCallingOrSelfPermission(java.lang.String param_0)
{
if (__ho3)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfPermission", args);
}
else
{
return super.checkCallingOrSelfPermission(param_0);
}
}
public int checkCallingOrSelfUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho4)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfUriPermission", args);
}
else
{
return super.checkCallingOrSelfUriPermission(param_0, param_1);
}
}
public int checkCallingPermission(java.lang.String param_0)
{
if (__ho5)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingPermission", args);
}
else
{
return super.checkCallingPermission(param_0);
}
}
public int checkCallingUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho6)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingUriPermission", args);
}
else
{
return super.checkCallingUriPermission(param_0, param_1);
}
}
public int checkPermission(java.lang.String param_0, int param_1, int param_2)
{
if (__ho7)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Integer)com.tns.Platform.callJSMethod(this, "checkPermission", args);
}
else
{
return super.checkPermission(param_0, param_1, param_2);
}
}
public int checkUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3)
{
if (__ho8)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (Integer)com.tns.Platform.callJSMethod(this, "checkUriPermission", args);
}
else
{
return super.checkUriPermission(param_0, param_1, param_2, param_3);
}
}
public int checkUriPermission(android.net.Uri param_0, java.lang.String param_1, java.lang.String param_2, int param_3, int param_4, int param_5)
{
if (__ho8)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
return (Integer)com.tns.Platform.callJSMethod(this, "checkUriPermission", args);
}
else
{
return super.checkUriPermission(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void clearWallpaper() throws java.io.IOException
{
if (__ho9)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "clearWallpaper", args);
}
else
{
super.clearWallpaper();
}
}
public void closeContextMenu()
{
if (__ho10)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "closeContextMenu", args);
}
else
{
super.closeContextMenu();
}
}
public void closeOptionsMenu()
{
if (__ho11)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "closeOptionsMenu", args);
}
else
{
super.closeOptionsMenu();
}
}
public android.content.Context createConfigurationContext(android.content.res.Configuration param_0)
{
if (__ho12)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createConfigurationContext", args);
}
else
{
return super.createConfigurationContext(param_0);
}
}
public android.content.Context createDisplayContext(android.view.Display param_0)
{
if (__ho13)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createDisplayContext", args);
}
else
{
return super.createDisplayContext(param_0);
}
}
public android.content.Context createPackageContext(java.lang.String param_0, int param_1) throws android.content.pm.PackageManager.NameNotFoundException
{
if (__ho14)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "createPackageContext", args);
}
else
{
return super.createPackageContext(param_0, param_1);
}
}
public android.app.PendingIntent createPendingResult(int param_0, android.content.Intent param_1, int param_2)
{
if (__ho15)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.app.PendingIntent)com.tns.Platform.callJSMethod(this, "createPendingResult", args);
}
else
{
return super.createPendingResult(param_0, param_1, param_2);
}
}
public java.lang.String[] databaseList()
{
if (__ho16)
{
Object[] args = null;
return (java.lang.String[])com.tns.Platform.callJSMethod(this, "databaseList", args);
}
else
{
return super.databaseList();
}
}
public boolean deleteDatabase(java.lang.String param_0)
{
if (__ho17)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "deleteDatabase", args);
}
else
{
return super.deleteDatabase(param_0);
}
}
public boolean deleteFile(java.lang.String param_0)
{
if (__ho18)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "deleteFile", args);
}
else
{
return super.deleteFile(param_0);
}
}
public boolean dispatchGenericMotionEvent(android.view.MotionEvent param_0)
{
if (__ho19)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchGenericMotionEvent", args);
}
else
{
return super.dispatchGenericMotionEvent(param_0);
}
}
public boolean dispatchKeyEvent(android.view.KeyEvent param_0)
{
if (__ho20)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyEvent", args);
}
else
{
return super.dispatchKeyEvent(param_0);
}
}
public boolean dispatchKeyShortcutEvent(android.view.KeyEvent param_0)
{
if (__ho21)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyShortcutEvent", args);
}
else
{
return super.dispatchKeyShortcutEvent(param_0);
}
}
public boolean dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent param_0)
{
if (__ho22)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchPopulateAccessibilityEvent", args);
}
else
{
return super.dispatchPopulateAccessibilityEvent(param_0);
}
}
public boolean dispatchTouchEvent(android.view.MotionEvent param_0)
{
if (__ho23)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchTouchEvent", args);
}
else
{
return super.dispatchTouchEvent(param_0);
}
}
public boolean dispatchTrackballEvent(android.view.MotionEvent param_0)
{
if (__ho24)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchTrackballEvent", args);
}
else
{
return super.dispatchTrackballEvent(param_0);
}
}
public void dump(java.lang.String param_0, java.io.FileDescriptor param_1, java.io.PrintWriter param_2, java.lang.String[] param_3)
{
if (__ho25)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "dump", args);
}
else
{
super.dump(param_0, param_1, param_2, param_3);
}
}
public void enforceCallingOrSelfPermission(java.lang.String param_0, java.lang.String param_1)
{
if (__ho26)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfPermission", args);
}
else
{
super.enforceCallingOrSelfPermission(param_0, param_1);
}
}
public void enforceCallingOrSelfUriPermission(android.net.Uri param_0, int param_1, java.lang.String param_2)
{
if (__ho27)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfUriPermission", args);
}
else
{
super.enforceCallingOrSelfUriPermission(param_0, param_1, param_2);
}
}
public void enforceCallingPermission(java.lang.String param_0, java.lang.String param_1)
{
if (__ho28)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "enforceCallingPermission", args);
}
else
{
super.enforceCallingPermission(param_0, param_1);
}
}
public void enforceCallingUriPermission(android.net.Uri param_0, int param_1, java.lang.String param_2)
{
if (__ho29)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "enforceCallingUriPermission", args);
}
else
{
super.enforceCallingUriPermission(param_0, param_1, param_2);
}
}
public void enforcePermission(java.lang.String param_0, int param_1, int param_2, java.lang.String param_3)
{
if (__ho30)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "enforcePermission", args);
}
else
{
super.enforcePermission(param_0, param_1, param_2, param_3);
}
}
public void enforceUriPermission(android.net.Uri param_0, java.lang.String param_1, java.lang.String param_2, int param_3, int param_4, int param_5, java.lang.String param_6)
{
if (__ho31)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "enforceUriPermission", args);
}
else
{
super.enforceUriPermission(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void enforceUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3, java.lang.String param_4)
{
if (__ho31)
{
Object[] args = new Object[5];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
com.tns.Platform.callJSMethod(this, "enforceUriPermission", args);
}
else
{
super.enforceUriPermission(param_0, param_1, param_2, param_3, param_4);
}
}
public boolean equals(java.lang.Object param_0)
{
if (__ho32)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "equals", args);
}
else
{
return super.equals(param_0);
}
}
public java.lang.String[] fileList()
{
if (__ho33)
{
Object[] args = null;
return (java.lang.String[])com.tns.Platform.callJSMethod(this, "fileList", args);
}
else
{
return super.fileList();
}
}
public android.view.View findViewById(int param_0)
{
if (__ho34)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.View)com.tns.Platform.callJSMethod(this, "findViewById", args);
}
else
{
return super.findViewById(param_0);
}
}
public void finish()
{
if (__ho35)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "finish", args);
}
else
{
super.finish();
}
}
public void finishActivity(int param_0)
{
if (__ho36)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "finishActivity", args);
}
else
{
super.finishActivity(param_0);
}
}
public void finishActivityFromChild(android.app.Activity param_0, int param_1)
{
if (__ho37)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "finishActivityFromChild", args);
}
else
{
super.finishActivityFromChild(param_0, param_1);
}
}
public void finishAffinity()
{
if (__ho38)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "finishAffinity", args);
}
else
{
super.finishAffinity();
}
}
public void finishFromChild(android.app.Activity param_0)
{
if (__ho39)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "finishFromChild", args);
}
else
{
super.finishFromChild(param_0);
}
}
public android.app.ActionBar getActionBar()
{
if (__ho40)
{
Object[] args = null;
return (android.app.ActionBar)com.tns.Platform.callJSMethod(this, "getActionBar", args);
}
else
{
return super.getActionBar();
}
}
public android.content.Context getApplicationContext()
{
if (__ho41)
{
Object[] args = null;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "getApplicationContext", args);
}
else
{
return super.getApplicationContext();
}
}
public android.content.pm.ApplicationInfo getApplicationInfo()
{
if (__ho42)
{
Object[] args = null;
return (android.content.pm.ApplicationInfo)com.tns.Platform.callJSMethod(this, "getApplicationInfo", args);
}
else
{
return super.getApplicationInfo();
}
}
public android.content.res.AssetManager getAssets()
{
if (__ho43)
{
Object[] args = null;
return (android.content.res.AssetManager)com.tns.Platform.callJSMethod(this, "getAssets", args);
}
else
{
return super.getAssets();
}
}
public android.content.Context getBaseContext()
{
if (__ho44)
{
Object[] args = null;
return (android.content.Context)com.tns.Platform.callJSMethod(this, "getBaseContext", args);
}
else
{
return super.getBaseContext();
}
}
public java.io.File getCacheDir()
{
if (__ho45)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getCacheDir", args);
}
else
{
return super.getCacheDir();
}
}
public android.content.ComponentName getCallingActivity()
{
if (__ho46)
{
Object[] args = null;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getCallingActivity", args);
}
else
{
return super.getCallingActivity();
}
}
public java.lang.String getCallingPackage()
{
if (__ho47)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getCallingPackage", args);
}
else
{
return super.getCallingPackage();
}
}
public int getChangingConfigurations()
{
if (__ho48)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "getChangingConfigurations", args);
}
else
{
return super.getChangingConfigurations();
}
}
public java.lang.ClassLoader getClassLoader()
{
if (__ho49)
{
Object[] args = null;
return (java.lang.ClassLoader)com.tns.Platform.callJSMethod(this, "getClassLoader", args);
}
else
{
return super.getClassLoader();
}
}
public android.content.ComponentName getComponentName()
{
if (__ho50)
{
Object[] args = null;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getComponentName", args);
}
else
{
return super.getComponentName();
}
}
public android.content.ContentResolver getContentResolver()
{
if (__ho51)
{
Object[] args = null;
return (android.content.ContentResolver)com.tns.Platform.callJSMethod(this, "getContentResolver", args);
}
else
{
return super.getContentResolver();
}
}
public android.view.View getCurrentFocus()
{
if (__ho52)
{
Object[] args = null;
return (android.view.View)com.tns.Platform.callJSMethod(this, "getCurrentFocus", args);
}
else
{
return super.getCurrentFocus();
}
}
public java.io.File getDatabasePath(java.lang.String param_0)
{
if (__ho53)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getDatabasePath", args);
}
else
{
return super.getDatabasePath(param_0);
}
}
public java.io.File getDir(java.lang.String param_0, int param_1)
{
if (__ho54)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getDir", args);
}
else
{
return super.getDir(param_0, param_1);
}
}
public java.io.File getExternalCacheDir()
{
if (__ho55)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalCacheDir", args);
}
else
{
return super.getExternalCacheDir();
}
}
public java.io.File getExternalFilesDir(java.lang.String param_0)
{
if (__ho56)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalFilesDir", args);
}
else
{
return super.getExternalFilesDir(param_0);
}
}
public java.io.File getFileStreamPath(java.lang.String param_0)
{
if (__ho57)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getFileStreamPath", args);
}
else
{
return super.getFileStreamPath(param_0);
}
}
public java.io.File getFilesDir()
{
if (__ho58)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getFilesDir", args);
}
else
{
return super.getFilesDir();
}
}
public android.app.FragmentManager getFragmentManager()
{
if (__ho59)
{
Object[] args = null;
return (android.app.FragmentManager)com.tns.Platform.callJSMethod(this, "getFragmentManager", args);
}
else
{
return super.getFragmentManager();
}
}
public android.content.Intent getIntent()
{
if (__ho60)
{
Object[] args = null;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getIntent", args);
}
else
{
return super.getIntent();
}
}
public java.lang.Object getLastNonConfigurationInstance()
{
if (__ho61)
{
Object[] args = null;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getLastNonConfigurationInstance", args);
}
else
{
return super.getLastNonConfigurationInstance();
}
}
public android.view.LayoutInflater getLayoutInflater()
{
if (__ho62)
{
Object[] args = null;
return (android.view.LayoutInflater)com.tns.Platform.callJSMethod(this, "getLayoutInflater", args);
}
else
{
return super.getLayoutInflater();
}
}
public android.app.LoaderManager getLoaderManager()
{
if (__ho63)
{
Object[] args = null;
return (android.app.LoaderManager)com.tns.Platform.callJSMethod(this, "getLoaderManager", args);
}
else
{
return super.getLoaderManager();
}
}
public java.lang.String getLocalClassName()
{
if (__ho64)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getLocalClassName", args);
}
else
{
return super.getLocalClassName();
}
}
public android.os.Looper getMainLooper()
{
if (__ho65)
{
Object[] args = null;
return (android.os.Looper)com.tns.Platform.callJSMethod(this, "getMainLooper", args);
}
else
{
return super.getMainLooper();
}
}
public android.view.MenuInflater getMenuInflater()
{
if (__ho66)
{
Object[] args = null;
return (android.view.MenuInflater)com.tns.Platform.callJSMethod(this, "getMenuInflater", args);
}
else
{
return super.getMenuInflater();
}
}
public java.io.File getObbDir()
{
if (__ho67)
{
Object[] args = null;
return (java.io.File)com.tns.Platform.callJSMethod(this, "getObbDir", args);
}
else
{
return super.getObbDir();
}
}
public java.lang.String getPackageCodePath()
{
if (__ho68)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageCodePath", args);
}
else
{
return super.getPackageCodePath();
}
}
public android.content.pm.PackageManager getPackageManager()
{
if (__ho69)
{
Object[] args = null;
return (android.content.pm.PackageManager)com.tns.Platform.callJSMethod(this, "getPackageManager", args);
}
else
{
return super.getPackageManager();
}
}
public java.lang.String getPackageName()
{
if (__ho70)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageName", args);
}
else
{
return super.getPackageName();
}
}
public java.lang.String getPackageResourcePath()
{
if (__ho71)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageResourcePath", args);
}
else
{
return super.getPackageResourcePath();
}
}
public android.content.Intent getParentActivityIntent()
{
if (__ho72)
{
Object[] args = null;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getParentActivityIntent", args);
}
else
{
return super.getParentActivityIntent();
}
}
public android.content.SharedPreferences getPreferences(int param_0)
{
if (__ho73)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getPreferences", args);
}
else
{
return super.getPreferences(param_0);
}
}
public int getRequestedOrientation()
{
if (__ho74)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "getRequestedOrientation", args);
}
else
{
return super.getRequestedOrientation();
}
}
public android.content.res.Resources getResources()
{
if (__ho75)
{
Object[] args = null;
return (android.content.res.Resources)com.tns.Platform.callJSMethod(this, "getResources", args);
}
else
{
return super.getResources();
}
}
public android.content.SharedPreferences getSharedPreferences(java.lang.String param_0, int param_1)
{
if (__ho76)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getSharedPreferences", args);
}
else
{
return super.getSharedPreferences(param_0, param_1);
}
}
public java.lang.Object getSystemService(java.lang.String param_0)
{
if (__ho77)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getSystemService", args);
}
else
{
return super.getSystemService(param_0);
}
}
public int getTaskId()
{
if (__ho78)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "getTaskId", args);
}
else
{
return super.getTaskId();
}
}
public android.content.res.Resources.Theme getTheme()
{
if (__ho79)
{
Object[] args = null;
return (android.content.res.Resources.Theme)com.tns.Platform.callJSMethod(this, "getTheme", args);
}
else
{
return super.getTheme();
}
}
public android.graphics.drawable.Drawable getWallpaper()
{
if (__ho80)
{
Object[] args = null;
return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "getWallpaper", args);
}
else
{
return super.getWallpaper();
}
}
public int getWallpaperDesiredMinimumHeight()
{
if (__ho81)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumHeight", args);
}
else
{
return super.getWallpaperDesiredMinimumHeight();
}
}
public int getWallpaperDesiredMinimumWidth()
{
if (__ho82)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumWidth", args);
}
else
{
return super.getWallpaperDesiredMinimumWidth();
}
}
public android.view.Window getWindow()
{
if (__ho83)
{
Object[] args = null;
return (android.view.Window)com.tns.Platform.callJSMethod(this, "getWindow", args);
}
else
{
return super.getWindow();
}
}
public android.view.WindowManager getWindowManager()
{
if (__ho84)
{
Object[] args = null;
return (android.view.WindowManager)com.tns.Platform.callJSMethod(this, "getWindowManager", args);
}
else
{
return super.getWindowManager();
}
}
public void grantUriPermission(java.lang.String param_0, android.net.Uri param_1, int param_2)
{
if (__ho85)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "grantUriPermission", args);
}
else
{
super.grantUriPermission(param_0, param_1, param_2);
}
}
public boolean hasWindowFocus()
{
if (__ho86)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "hasWindowFocus", args);
}
else
{
return super.hasWindowFocus();
}
}
public int hashCode()
{
if (__ho87)
{
Object[] args = null;
return (Integer)com.tns.Platform.callJSMethod(this, "hashCode", args);
}
else
{
return super.hashCode();
}
}
public void invalidateOptionsMenu()
{
if (__ho88)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "invalidateOptionsMenu", args);
}
else
{
super.invalidateOptionsMenu();
}
}
public boolean isChangingConfigurations()
{
if (__ho89)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "isChangingConfigurations", args);
}
else
{
return super.isChangingConfigurations();
}
}
public boolean isDestroyed()
{
if (__ho90)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "isDestroyed", args);
}
else
{
return super.isDestroyed();
}
}
public boolean isFinishing()
{
if (__ho91)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "isFinishing", args);
}
else
{
return super.isFinishing();
}
}
public boolean isRestricted()
{
if (__ho92)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "isRestricted", args);
}
else
{
return super.isRestricted();
}
}
public boolean isTaskRoot()
{
if (__ho93)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "isTaskRoot", args);
}
else
{
return super.isTaskRoot();
}
}
public boolean moveTaskToBack(boolean param_0)
{
if (__ho94)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "moveTaskToBack", args);
}
else
{
return super.moveTaskToBack(param_0);
}
}
public boolean navigateUpTo(android.content.Intent param_0)
{
if (__ho95)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "navigateUpTo", args);
}
else
{
return super.navigateUpTo(param_0);
}
}
public boolean navigateUpToFromChild(android.app.Activity param_0, android.content.Intent param_1)
{
if (__ho96)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "navigateUpToFromChild", args);
}
else
{
return super.navigateUpToFromChild(param_0, param_1);
}
}
public void onActionModeFinished(android.view.ActionMode param_0)
{
if (__ho97)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onActionModeFinished", args);
}
else
{
super.onActionModeFinished(param_0);
}
}
public void onActionModeStarted(android.view.ActionMode param_0)
{
if (__ho98)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onActionModeStarted", args);
}
else
{
super.onActionModeStarted(param_0);
}
}
protected void onActivityResult(int param_0, int param_1, android.content.Intent param_2)
{
if (__ho99)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onActivityResult", args);
}
else
{
super.onActivityResult(param_0, param_1, param_2);
}
}
protected void onApplyThemeResource(android.content.res.Resources.Theme param_0, int param_1, boolean param_2)
{
if (__ho100)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onApplyThemeResource", args);
}
else
{
super.onApplyThemeResource(param_0, param_1, param_2);
}
}
public void onAttachFragment(android.app.Fragment param_0)
{
if (__ho101)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onAttachFragment", args);
}
else
{
super.onAttachFragment(param_0);
}
}
public void onAttachedToWindow()
{
if (__ho102)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onAttachedToWindow", args);
}
else
{
super.onAttachedToWindow();
}
}
public void onBackPressed()
{
if (__ho103)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onBackPressed", args);
}
else
{
super.onBackPressed();
}
}
protected void onChildTitleChanged(android.app.Activity param_0, java.lang.CharSequence param_1)
{
if (__ho104)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onChildTitleChanged", args);
}
else
{
super.onChildTitleChanged(param_0, param_1);
}
}
public void onConfigurationChanged(android.content.res.Configuration param_0)
{
if (__ho105)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onConfigurationChanged", args);
}
else
{
super.onConfigurationChanged(param_0);
}
}
public void onContentChanged()
{
if (__ho106)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onContentChanged", args);
}
else
{
super.onContentChanged();
}
}
public boolean onContextItemSelected(android.view.MenuItem param_0)
{
if (__ho107)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onContextItemSelected", args);
}
else
{
return super.onContextItemSelected(param_0);
}
}
public void onContextMenuClosed(android.view.Menu param_0)
{
if (__ho108)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onContextMenuClosed", args);
}
else
{
super.onContextMenuClosed(param_0);
}
}
private native String[] getMethodOverrides(int objectId, Object[] packagesArgs);
protected void onCreate(android.os.Bundle param_0)
{
Object[] packagesArgs = Platform.packageArgs(this);
String[] methodOverrides = getMethodOverrides(objectId, packagesArgs);
setMethodOverrides(methodOverrides);
if (__ho109)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onCreate", args);
android.util.Log.d(com.tns.Platform.DEFAULT_LOG_TAG, "NativeScriptActivity.onCreate called");
}
else
{
super.onCreate(param_0);
}
}
public void onCreateContextMenu(android.view.ContextMenu param_0, android.view.View param_1, android.view.ContextMenu.ContextMenuInfo param_2)
{
if (__ho110)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onCreateContextMenu", args);
}
else
{
super.onCreateContextMenu(param_0, param_1, param_2);
}
}
public java.lang.CharSequence onCreateDescription()
{
if (__ho111)
{
Object[] args = null;
return (java.lang.CharSequence)com.tns.Platform.callJSMethod(this, "onCreateDescription", args);
}
else
{
return super.onCreateDescription();
}
}
protected android.app.Dialog onCreateDialog(int param_0, android.os.Bundle param_1)
{
if (__ho112)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", args);
}
else
{
return super.onCreateDialog(param_0, param_1);
}
}
protected android.app.Dialog onCreateDialog(int param_0)
{
if (__ho112)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", args);
}
else
{
return super.onCreateDialog(param_0);
}
}
public void onCreateNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
{
if (__ho113)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onCreateNavigateUpTaskStack", args);
}
else
{
super.onCreateNavigateUpTaskStack(param_0);
}
}
public boolean onCreateOptionsMenu(android.view.Menu param_0)
{
if (__ho114)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onCreateOptionsMenu", args);
}
else
{
return super.onCreateOptionsMenu(param_0);
}
}
public boolean onCreatePanelMenu(int param_0, android.view.Menu param_1)
{
if (__ho115)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onCreatePanelMenu", args);
}
else
{
return super.onCreatePanelMenu(param_0, param_1);
}
}
public android.view.View onCreatePanelView(int param_0)
{
if (__ho116)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreatePanelView", args);
}
else
{
return super.onCreatePanelView(param_0);
}
}
public boolean onCreateThumbnail(android.graphics.Bitmap param_0, android.graphics.Canvas param_1)
{
if (__ho117)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onCreateThumbnail", args);
}
else
{
return super.onCreateThumbnail(param_0, param_1);
}
}
public android.view.View onCreateView(java.lang.String param_0, android.content.Context param_1, android.util.AttributeSet param_2)
{
if (__ho118)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", args);
}
else
{
return super.onCreateView(param_0, param_1, param_2);
}
}
public android.view.View onCreateView(android.view.View param_0, java.lang.String param_1, android.content.Context param_2, android.util.AttributeSet param_3)
{
if (__ho118)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", args);
}
else
{
return super.onCreateView(param_0, param_1, param_2, param_3);
}
}
protected void onDestroy()
{
if (__ho119)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onDestroy", args);
}
else
{
super.onDestroy();
}
// TODO: remove from com.tns.Platform.strongInstances
}
public void onDetachedFromWindow()
{
if (__ho120)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onDetachedFromWindow", args);
}
else
{
super.onDetachedFromWindow();
}
}
public boolean onGenericMotionEvent(android.view.MotionEvent param_0)
{
if (__ho121)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onGenericMotionEvent", args);
}
else
{
return super.onGenericMotionEvent(param_0);
}
}
public boolean onKeyDown(int param_0, android.view.KeyEvent param_1)
{
if (__ho122)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyDown", args);
}
else
{
return super.onKeyDown(param_0, param_1);
}
}
public boolean onKeyLongPress(int param_0, android.view.KeyEvent param_1)
{
if (__ho123)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyLongPress", args);
}
else
{
return super.onKeyLongPress(param_0, param_1);
}
}
public boolean onKeyMultiple(int param_0, int param_1, android.view.KeyEvent param_2)
{
if (__ho124)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyMultiple", args);
}
else
{
return super.onKeyMultiple(param_0, param_1, param_2);
}
}
public boolean onKeyShortcut(int param_0, android.view.KeyEvent param_1)
{
if (__ho125)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyShortcut", args);
}
else
{
return super.onKeyShortcut(param_0, param_1);
}
}
public boolean onKeyUp(int param_0, android.view.KeyEvent param_1)
{
if (__ho126)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyUp", args);
}
else
{
return super.onKeyUp(param_0, param_1);
}
}
public void onLowMemory()
{
if (__ho127)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onLowMemory", args);
}
else
{
super.onLowMemory();
}
}
public boolean onMenuItemSelected(int param_0, android.view.MenuItem param_1)
{
if (__ho128)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onMenuItemSelected", args);
}
else
{
return super.onMenuItemSelected(param_0, param_1);
}
}
public boolean onMenuOpened(int param_0, android.view.Menu param_1)
{
if (__ho129)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "onMenuOpened", args);
}
else
{
return super.onMenuOpened(param_0, param_1);
}
}
public boolean onNavigateUp()
{
if (__ho130)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "onNavigateUp", args);
}
else
{
return super.onNavigateUp();
}
}
public boolean onNavigateUpFromChild(android.app.Activity param_0)
{
if (__ho131)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onNavigateUpFromChild", args);
}
else
{
return super.onNavigateUpFromChild(param_0);
}
}
protected void onNewIntent(android.content.Intent param_0)
{
if (__ho132)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onNewIntent", args);
}
else
{
super.onNewIntent(param_0);
}
}
public boolean onOptionsItemSelected(android.view.MenuItem param_0)
{
if (__ho133)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onOptionsItemSelected", args);
}
else
{
return super.onOptionsItemSelected(param_0);
}
}
public void onOptionsMenuClosed(android.view.Menu param_0)
{
if (__ho134)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onOptionsMenuClosed", args);
}
else
{
super.onOptionsMenuClosed(param_0);
}
}
public void onPanelClosed(int param_0, android.view.Menu param_1)
{
if (__ho135)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onPanelClosed", args);
}
else
{
super.onPanelClosed(param_0, param_1);
}
}
protected void onPause()
{
if (__ho136)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onPause", args);
}
else
{
super.onPause();
}
}
protected void onPostCreate(android.os.Bundle param_0)
{
if (__ho137)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onPostCreate", args);
}
else
{
super.onPostCreate(param_0);
}
}
protected void onPostResume()
{
if (__ho138)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onPostResume", args);
}
else
{
super.onPostResume();
}
}
protected void onPrepareDialog(int param_0, android.app.Dialog param_1)
{
if (__ho139)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onPrepareDialog", args);
}
else
{
super.onPrepareDialog(param_0, param_1);
}
}
protected void onPrepareDialog(int param_0, android.app.Dialog param_1, android.os.Bundle param_2)
{
if (__ho139)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "onPrepareDialog", args);
}
else
{
super.onPrepareDialog(param_0, param_1, param_2);
}
}
public void onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
{
if (__ho140)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onPrepareNavigateUpTaskStack", args);
}
else
{
super.onPrepareNavigateUpTaskStack(param_0);
}
}
public boolean onPrepareOptionsMenu(android.view.Menu param_0)
{
if (__ho141)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onPrepareOptionsMenu", args);
}
else
{
return super.onPrepareOptionsMenu(param_0);
}
}
public boolean onPreparePanel(int param_0, android.view.View param_1, android.view.Menu param_2)
{
if (__ho142)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Boolean)com.tns.Platform.callJSMethod(this, "onPreparePanel", args);
}
else
{
return super.onPreparePanel(param_0, param_1, param_2);
}
}
protected void onRestart()
{
if (__ho143)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onRestart", args);
}
else
{
super.onRestart();
}
}
protected void onRestoreInstanceState(android.os.Bundle param_0)
{
if (__ho144)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onRestoreInstanceState", args);
}
else
{
super.onRestoreInstanceState(param_0);
}
}
protected void onResume()
{
if (__ho145)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onResume", args);
}
else
{
super.onResume();
}
}
public java.lang.Object onRetainNonConfigurationInstance()
{
if (__ho146)
{
Object[] args = null;
return (java.lang.Object)com.tns.Platform.callJSMethod(this, "onRetainNonConfigurationInstance", args);
}
else
{
return super.onRetainNonConfigurationInstance();
}
}
protected void onSaveInstanceState(android.os.Bundle param_0)
{
if (__ho147)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onSaveInstanceState", args);
}
else
{
super.onSaveInstanceState(param_0);
}
}
public boolean onSearchRequested()
{
if (__ho148)
{
Object[] args = null;
return (Boolean)com.tns.Platform.callJSMethod(this, "onSearchRequested", args);
}
else
{
return super.onSearchRequested();
}
}
protected void onStart()
{
if (__ho149)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onStart", args);
}
else
{
super.onStart();
}
}
protected void onStop()
{
if (__ho150)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onStop", args);
}
else
{
super.onStop();
}
}
protected void onTitleChanged(java.lang.CharSequence param_0, int param_1)
{
if (__ho151)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "onTitleChanged", args);
}
else
{
super.onTitleChanged(param_0, param_1);
}
}
public boolean onTouchEvent(android.view.MotionEvent param_0)
{
if (__ho152)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onTouchEvent", args);
}
else
{
return super.onTouchEvent(param_0);
}
}
public boolean onTrackballEvent(android.view.MotionEvent param_0)
{
if (__ho153)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "onTrackballEvent", args);
}
else
{
return super.onTrackballEvent(param_0);
}
}
public void onTrimMemory(int param_0)
{
if (__ho154)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onTrimMemory", args);
}
else
{
super.onTrimMemory(param_0);
}
}
public void onUserInteraction()
{
if (__ho155)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onUserInteraction", args);
}
else
{
super.onUserInteraction();
}
}
protected void onUserLeaveHint()
{
if (__ho156)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "onUserLeaveHint", args);
}
else
{
super.onUserLeaveHint();
}
}
public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams param_0)
{
if (__ho157)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onWindowAttributesChanged", args);
}
else
{
super.onWindowAttributesChanged(param_0);
}
}
public void onWindowFocusChanged(boolean param_0)
{
if (__ho158)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "onWindowFocusChanged", args);
}
else
{
super.onWindowFocusChanged(param_0);
}
}
public android.view.ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback param_0)
{
if (__ho159)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "onWindowStartingActionMode", args);
}
else
{
return super.onWindowStartingActionMode(param_0);
}
}
public void openContextMenu(android.view.View param_0)
{
if (__ho160)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "openContextMenu", args);
}
else
{
super.openContextMenu(param_0);
}
}
public java.io.FileInputStream openFileInput(java.lang.String param_0) throws java.io.FileNotFoundException
{
if (__ho161)
{
Object[] args = new Object[1];
args[0] = param_0;
return (java.io.FileInputStream)com.tns.Platform.callJSMethod(this, "openFileInput", args);
}
else
{
return super.openFileInput(param_0);
}
}
public java.io.FileOutputStream openFileOutput(java.lang.String param_0, int param_1) throws java.io.FileNotFoundException
{
if (__ho162)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (java.io.FileOutputStream)com.tns.Platform.callJSMethod(this, "openFileOutput", args);
}
else
{
return super.openFileOutput(param_0, param_1);
}
}
public void openOptionsMenu()
{
if (__ho163)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "openOptionsMenu", args);
}
else
{
super.openOptionsMenu();
}
}
public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2, android.database.DatabaseErrorHandler param_3)
{
if (__ho164)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", args);
}
else
{
return super.openOrCreateDatabase(param_0, param_1, param_2, param_3);
}
}
public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2)
{
if (__ho164)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", args);
}
else
{
return super.openOrCreateDatabase(param_0, param_1, param_2);
}
}
public void overridePendingTransition(int param_0, int param_1)
{
if (__ho165)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "overridePendingTransition", args);
}
else
{
super.overridePendingTransition(param_0, param_1);
}
}
public android.graphics.drawable.Drawable peekWallpaper()
{
if (__ho166)
{
Object[] args = null;
return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "peekWallpaper", args);
}
else
{
return super.peekWallpaper();
}
}
public void recreate()
{
if (__ho167)
{
Object[] args = null;
com.tns.Platform.callJSMethod(this, "recreate", args);
}
else
{
super.recreate();
}
}
public void registerComponentCallbacks(android.content.ComponentCallbacks param_0)
{
if (__ho168)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "registerComponentCallbacks", args);
}
else
{
super.registerComponentCallbacks(param_0);
}
}
public void registerForContextMenu(android.view.View param_0)
{
if (__ho169)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "registerForContextMenu", args);
}
else
{
super.registerForContextMenu(param_0);
}
}
public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1, java.lang.String param_2, android.os.Handler param_3)
{
if (__ho170)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", args);
}
else
{
return super.registerReceiver(param_0, param_1, param_2, param_3);
}
}
public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1)
{
if (__ho170)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", args);
}
else
{
return super.registerReceiver(param_0, param_1);
}
}
public void removeStickyBroadcast(android.content.Intent param_0)
{
if (__ho171)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "removeStickyBroadcast", args);
}
else
{
super.removeStickyBroadcast(param_0);
}
}
public void removeStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho172)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "removeStickyBroadcastAsUser", args);
}
else
{
super.removeStickyBroadcastAsUser(param_0, param_1);
}
}
public void revokeUriPermission(android.net.Uri param_0, int param_1)
{
if (__ho173)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "revokeUriPermission", args);
}
else
{
super.revokeUriPermission(param_0, param_1);
}
}
public void sendBroadcast(android.content.Intent param_0, java.lang.String param_1)
{
if (__ho174)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendBroadcast", args);
}
else
{
super.sendBroadcast(param_0, param_1);
}
}
public void sendBroadcast(android.content.Intent param_0)
{
if (__ho174)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "sendBroadcast", args);
}
else
{
super.sendBroadcast(param_0);
}
}
public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho175)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", args);
}
else
{
super.sendBroadcastAsUser(param_0, param_1);
}
}
public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2)
{
if (__ho175)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", args);
}
else
{
super.sendBroadcastAsUser(param_0, param_1, param_2);
}
}
public void sendOrderedBroadcast(android.content.Intent param_0, java.lang.String param_1, android.content.BroadcastReceiver param_2, android.os.Handler param_3, int param_4, java.lang.String param_5, android.os.Bundle param_6)
{
if (__ho176)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", args);
}
else
{
super.sendOrderedBroadcast(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void sendOrderedBroadcast(android.content.Intent param_0, java.lang.String param_1)
{
if (__ho176)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", args);
}
else
{
super.sendOrderedBroadcast(param_0, param_1);
}
}
public void sendOrderedBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2, android.content.BroadcastReceiver param_3, android.os.Handler param_4, int param_5, java.lang.String param_6, android.os.Bundle param_7)
{
if (__ho177)
{
Object[] args = new Object[8];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
args[7] = param_7;
com.tns.Platform.callJSMethod(this, "sendOrderedBroadcastAsUser", args);
}
else
{
super.sendOrderedBroadcastAsUser(param_0, param_1, param_2, param_3, param_4, param_5, param_6, param_7);
}
}
public void sendStickyBroadcast(android.content.Intent param_0)
{
if (__ho178)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "sendStickyBroadcast", args);
}
else
{
super.sendStickyBroadcast(param_0);
}
}
public void sendStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
{
if (__ho179)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "sendStickyBroadcastAsUser", args);
}
else
{
super.sendStickyBroadcastAsUser(param_0, param_1);
}
}
public void sendStickyOrderedBroadcast(android.content.Intent param_0, android.content.BroadcastReceiver param_1, android.os.Handler param_2, int param_3, java.lang.String param_4, android.os.Bundle param_5)
{
if (__ho180)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcast", args);
}
else
{
super.sendStickyOrderedBroadcast(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void sendStickyOrderedBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, android.content.BroadcastReceiver param_2, android.os.Handler param_3, int param_4, java.lang.String param_5, android.os.Bundle param_6)
{
if (__ho181)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcastAsUser", args);
}
else
{
super.sendStickyOrderedBroadcastAsUser(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void setContentView(int param_0)
{
if (__ho182)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setContentView", args);
}
else
{
super.setContentView(param_0);
}
}
public void setContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
{
if (__ho182)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "setContentView", args);
}
else
{
super.setContentView(param_0, param_1);
}
}
public void setContentView(android.view.View param_0)
{
if (__ho182)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setContentView", args);
}
else
{
super.setContentView(param_0);
}
}
public void setFinishOnTouchOutside(boolean param_0)
{
if (__ho183)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setFinishOnTouchOutside", args);
}
else
{
super.setFinishOnTouchOutside(param_0);
}
}
public void setIntent(android.content.Intent param_0)
{
if (__ho184)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setIntent", args);
}
else
{
super.setIntent(param_0);
}
}
public void setRequestedOrientation(int param_0)
{
if (__ho185)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setRequestedOrientation", args);
}
else
{
super.setRequestedOrientation(param_0);
}
}
public void setTheme(int param_0)
{
if (__ho186)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTheme", args);
}
else
{
super.setTheme(param_0);
}
}
public void setTitle(java.lang.CharSequence param_0)
{
if (__ho187)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitle", args);
}
else
{
super.setTitle(param_0);
}
}
public void setTitle(int param_0)
{
if (__ho187)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitle", args);
}
else
{
super.setTitle(param_0);
}
}
public void setTitleColor(int param_0)
{
if (__ho188)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setTitleColor", args);
}
else
{
super.setTitleColor(param_0);
}
}
public void setVisible(boolean param_0)
{
if (__ho189)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setVisible", args);
}
else
{
super.setVisible(param_0);
}
}
public void setWallpaper(java.io.InputStream param_0) throws java.io.IOException
{
if (__ho190)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setWallpaper", args);
}
else
{
super.setWallpaper(param_0);
}
}
public void setWallpaper(android.graphics.Bitmap param_0) throws java.io.IOException
{
if (__ho190)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "setWallpaper", args);
}
else
{
super.setWallpaper(param_0);
}
}
public boolean shouldUpRecreateTask(android.content.Intent param_0)
{
if (__ho191)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "shouldUpRecreateTask", args);
}
else
{
return super.shouldUpRecreateTask(param_0);
}
}
public android.view.ActionMode startActionMode(android.view.ActionMode.Callback param_0)
{
if (__ho192)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "startActionMode", args);
}
else
{
return super.startActionMode(param_0);
}
}
public void startActivities(android.content.Intent[] param_0, android.os.Bundle param_1)
{
if (__ho193)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivities", args);
}
else
{
super.startActivities(param_0, param_1);
}
}
public void startActivities(android.content.Intent[] param_0)
{
if (__ho193)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startActivities", args);
}
else
{
super.startActivities(param_0);
}
}
public void startActivity(android.content.Intent param_0, android.os.Bundle param_1)
{
if (__ho194)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivity", args);
}
else
{
super.startActivity(param_0, param_1);
}
}
public void startActivity(android.content.Intent param_0)
{
if (__ho194)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startActivity", args);
}
else
{
super.startActivity(param_0);
}
}
public void startActivityForResult(android.content.Intent param_0, int param_1)
{
if (__ho195)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "startActivityForResult", args);
}
else
{
super.startActivityForResult(param_0, param_1);
}
}
public void startActivityForResult(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
{
if (__ho195)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityForResult", args);
}
else
{
super.startActivityForResult(param_0, param_1, param_2);
}
}
public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
{
if (__ho196)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startActivityFromChild", args);
}
else
{
super.startActivityFromChild(param_0, param_1, param_2, param_3);
}
}
public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2)
{
if (__ho196)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityFromChild", args);
}
else
{
super.startActivityFromChild(param_0, param_1, param_2);
}
}
public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2)
{
if (__ho197)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Platform.callJSMethod(this, "startActivityFromFragment", args);
}
else
{
super.startActivityFromFragment(param_0, param_1, param_2);
}
}
public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
{
if (__ho197)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startActivityFromFragment", args);
}
else
{
super.startActivityFromFragment(param_0, param_1, param_2, param_3);
}
}
public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1)
{
if (__ho198)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", args);
}
else
{
return super.startActivityIfNeeded(param_0, param_1);
}
}
public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
{
if (__ho198)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", args);
}
else
{
return super.startActivityIfNeeded(param_0, param_1, param_2);
}
}
public boolean startInstrumentation(android.content.ComponentName param_0, java.lang.String param_1, android.os.Bundle param_2)
{
if (__ho199)
{
Object[] args = new Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
return (Boolean)com.tns.Platform.callJSMethod(this, "startInstrumentation", args);
}
else
{
return super.startInstrumentation(param_0, param_1, param_2);
}
}
public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4, android.os.Bundle param_5) throws android.content.IntentSender.SendIntentException
{
if (__ho200)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "startIntentSender", args);
}
else
{
super.startIntentSender(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4) throws android.content.IntentSender.SendIntentException
{
if (__ho200)
{
Object[] args = new Object[5];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
com.tns.Platform.callJSMethod(this, "startIntentSender", args);
}
else
{
super.startIntentSender(param_0, param_1, param_2, param_3, param_4);
}
}
public void startIntentSenderForResult(android.content.IntentSender param_0, int param_1, android.content.Intent param_2, int param_3, int param_4, int param_5, android.os.Bundle param_6) throws android.content.IntentSender.SendIntentException
{
if (__ho201)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", args);
}
else
{
super.startIntentSenderForResult(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void startIntentSenderForResult(android.content.IntentSender param_0, int param_1, android.content.Intent param_2, int param_3, int param_4, int param_5) throws android.content.IntentSender.SendIntentException
{
if (__ho201)
{
Object[] args = new Object[6];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", args);
}
else
{
super.startIntentSenderForResult(param_0, param_1, param_2, param_3, param_4, param_5);
}
}
public void startIntentSenderFromChild(android.app.Activity param_0, android.content.IntentSender param_1, int param_2, android.content.Intent param_3, int param_4, int param_5, int param_6, android.os.Bundle param_7) throws android.content.IntentSender.SendIntentException
{
if (__ho202)
{
Object[] args = new Object[8];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
args[7] = param_7;
com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", args);
}
else
{
super.startIntentSenderFromChild(param_0, param_1, param_2, param_3, param_4, param_5, param_6, param_7);
}
}
public void startIntentSenderFromChild(android.app.Activity param_0, android.content.IntentSender param_1, int param_2, android.content.Intent param_3, int param_4, int param_5, int param_6) throws android.content.IntentSender.SendIntentException
{
if (__ho202)
{
Object[] args = new Object[7];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
args[4] = param_4;
args[5] = param_5;
args[6] = param_6;
com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", args);
}
else
{
super.startIntentSenderFromChild(param_0, param_1, param_2, param_3, param_4, param_5, param_6);
}
}
public void startManagingCursor(android.database.Cursor param_0)
{
if (__ho203)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "startManagingCursor", args);
}
else
{
super.startManagingCursor(param_0);
}
}
public boolean startNextMatchingActivity(android.content.Intent param_0)
{
if (__ho204)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", args);
}
else
{
return super.startNextMatchingActivity(param_0);
}
}
public boolean startNextMatchingActivity(android.content.Intent param_0, android.os.Bundle param_1)
{
if (__ho204)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
return (Boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", args);
}
else
{
return super.startNextMatchingActivity(param_0, param_1);
}
}
public void startSearch(java.lang.String param_0, boolean param_1, android.os.Bundle param_2, boolean param_3)
{
if (__ho205)
{
Object[] args = new Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Platform.callJSMethod(this, "startSearch", args);
}
else
{
super.startSearch(param_0, param_1, param_2, param_3);
}
}
public android.content.ComponentName startService(android.content.Intent param_0)
{
if (__ho206)
{
Object[] args = new Object[1];
args[0] = param_0;
return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "startService", args);
}
else
{
return super.startService(param_0);
}
}
public void stopManagingCursor(android.database.Cursor param_0)
{
if (__ho207)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "stopManagingCursor", args);
}
else
{
super.stopManagingCursor(param_0);
}
}
public boolean stopService(android.content.Intent param_0)
{
if (__ho208)
{
Object[] args = new Object[1];
args[0] = param_0;
return (Boolean)com.tns.Platform.callJSMethod(this, "stopService", args);
}
else
{
return super.stopService(param_0);
}
}
public void takeKeyEvents(boolean param_0)
{
if (__ho209)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "takeKeyEvents", args);
}
else
{
super.takeKeyEvents(param_0);
}
}
public java.lang.String toString()
{
if (__ho210)
{
Object[] args = null;
return (java.lang.String)com.tns.Platform.callJSMethod(this, "toString", args);
}
else
{
return super.toString();
}
}
public void triggerSearch(java.lang.String param_0, android.os.Bundle param_1)
{
if (__ho211)
{
Object[] args = new Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Platform.callJSMethod(this, "triggerSearch", args);
}
else
{
super.triggerSearch(param_0, param_1);
}
}
public void unbindService(android.content.ServiceConnection param_0)
{
if (__ho212)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unbindService", args);
}
else
{
super.unbindService(param_0);
}
}
public void unregisterComponentCallbacks(android.content.ComponentCallbacks param_0)
{
if (__ho213)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterComponentCallbacks", args);
}
else
{
super.unregisterComponentCallbacks(param_0);
}
}
public void unregisterForContextMenu(android.view.View param_0)
{
if (__ho214)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterForContextMenu", args);
}
else
{
super.unregisterForContextMenu(param_0);
}
}
public void unregisterReceiver(android.content.BroadcastReceiver param_0)
{
if (__ho215)
{
Object[] args = new Object[1];
args[0] = param_0;
com.tns.Platform.callJSMethod(this, "unregisterReceiver", args);
}
else
{
super.unregisterReceiver(param_0);
}
}
private void setMethodOverrides(String[] methodOverrides)
{
for (String m: methodOverrides)
{
if (m.equals("onChildTitleChanged")) __ho104= true;
if (m.equals("getChangingConfigurations")) __ho48= true;
if (m.equals("getObbDir")) __ho67= true;
if (m.equals("onSearchRequested")) __ho148= true;
if (m.equals("navigateUpToFromChild")) __ho96= true;
if (m.equals("deleteDatabase")) __ho17= true;
if (m.equals("checkPermission")) __ho7= true;
if (m.equals("enforceUriPermission")) __ho31= true;
if (m.equals("startActivityFromFragment")) __ho197= true;
if (m.equals("databaseList")) __ho16= true;
if (m.equals("dispatchGenericMotionEvent")) __ho19= true;
if (m.equals("getFilesDir")) __ho58= true;
if (m.equals("sendStickyOrderedBroadcastAsUser")) __ho181= true;
if (m.equals("fileList")) __ho33= true;
if (m.equals("getWallpaper")) __ho80= true;
if (m.equals("onBackPressed")) __ho103= true;
if (m.equals("onRestart")) __ho143= true;
if (m.equals("shouldUpRecreateTask")) __ho191= true;
if (m.equals("finishAffinity")) __ho38= true;
if (m.equals("setIntent")) __ho184= true;
if (m.equals("unregisterComponentCallbacks")) __ho213= true;
if (m.equals("dispatchPopulateAccessibilityEvent")) __ho22= true;
if (m.equals("getLoaderManager")) __ho63= true;
if (m.equals("startIntentSender")) __ho200= true;
if (m.equals("openOrCreateDatabase")) __ho164= true;
if (m.equals("getFileStreamPath")) __ho57= true;
if (m.equals("closeOptionsMenu")) __ho11= true;
if (m.equals("getWallpaperDesiredMinimumHeight")) __ho81= true;
if (m.equals("getCallingActivity")) __ho46= true;
if (m.equals("openOptionsMenu")) __ho163= true;
if (m.equals("onWindowAttributesChanged")) __ho157= true;
if (m.equals("invalidateOptionsMenu")) __ho88= true;
if (m.equals("onCreateNavigateUpTaskStack")) __ho113= true;
if (m.equals("removeStickyBroadcast")) __ho171= true;
if (m.equals("dispatchKeyEvent")) __ho20= true;
if (m.equals("getCurrentFocus")) __ho52= true;
if (m.equals("peekWallpaper")) __ho166= true;
if (m.equals("createConfigurationContext")) __ho12= true;
if (m.equals("getApplicationContext")) __ho41= true;
if (m.equals("sendStickyBroadcast")) __ho178= true;
if (m.equals("getResources")) __ho75= true;
if (m.equals("onOptionsMenuClosed")) __ho134= true;
if (m.equals("getSharedPreferences")) __ho76= true;
if (m.equals("setFinishOnTouchOutside")) __ho183= true;
if (m.equals("onAttachedToWindow")) __ho102= true;
if (m.equals("getWallpaperDesiredMinimumWidth")) __ho82= true;
if (m.equals("startInstrumentation")) __ho199= true;
if (m.equals("onPrepareOptionsMenu")) __ho141= true;
if (m.equals("getComponentName")) __ho50= true;
if (m.equals("sendStickyBroadcastAsUser")) __ho179= true;
if (m.equals("setWallpaper")) __ho190= true;
if (m.equals("stopManagingCursor")) __ho207= true;
if (m.equals("getParentActivityIntent")) __ho72= true;
if (m.equals("onTrimMemory")) __ho154= true;
if (m.equals("onActionModeFinished")) __ho97= true;
if (m.equals("recreate")) __ho167= true;
if (m.equals("sendStickyOrderedBroadcast")) __ho180= true;
if (m.equals("onCreateDialog")) __ho112= true;
if (m.equals("startActivityForResult")) __ho195= true;
if (m.equals("onTitleChanged")) __ho151= true;
if (m.equals("getActionBar")) __ho40= true;
if (m.equals("onCreatePanelView")) __ho116= true;
if (m.equals("onNewIntent")) __ho132= true;
if (m.equals("onKeyMultiple")) __ho124= true;
if (m.equals("toString")) __ho210= true;
if (m.equals("applyOverrideConfiguration")) __ho1= true;
if (m.equals("getFragmentManager")) __ho59= true;
if (m.equals("onPanelClosed")) __ho135= true;
if (m.equals("createDisplayContext")) __ho13= true;
if (m.equals("onKeyShortcut")) __ho125= true;
if (m.equals("dispatchTrackballEvent")) __ho24= true;
if (m.equals("addContentView")) __ho0= true;
if (m.equals("onActivityResult")) __ho99= true;
if (m.equals("openFileInput")) __ho161= true;
if (m.equals("getRequestedOrientation")) __ho74= true;
if (m.equals("getWindowManager")) __ho84= true;
if (m.equals("triggerSearch")) __ho211= true;
if (m.equals("finish")) __ho35= true;
if (m.equals("dispatchKeyShortcutEvent")) __ho21= true;
if (m.equals("setVisible")) __ho189= true;
if (m.equals("isDestroyed")) __ho90= true;
if (m.equals("setTitle")) __ho187= true;
if (m.equals("startActivities")) __ho193= true;
if (m.equals("onKeyLongPress")) __ho123= true;
if (m.equals("onGenericMotionEvent")) __ho121= true;
if (m.equals("getMenuInflater")) __ho66= true;
if (m.equals("isChangingConfigurations")) __ho89= true;
if (m.equals("getPackageName")) __ho70= true;
if (m.equals("setRequestedOrientation")) __ho185= true;
if (m.equals("enforceCallingUriPermission")) __ho29= true;
if (m.equals("getLocalClassName")) __ho64= true;
if (m.equals("getWindow")) __ho83= true;
if (m.equals("onRestoreInstanceState")) __ho144= true;
if (m.equals("checkCallingOrSelfUriPermission")) __ho4= true;
if (m.equals("setTitleColor")) __ho188= true;
if (m.equals("getClassLoader")) __ho49= true;
if (m.equals("closeContextMenu")) __ho10= true;
if (m.equals("createPackageContext")) __ho14= true;
if (m.equals("openFileOutput")) __ho162= true;
if (m.equals("moveTaskToBack")) __ho94= true;
if (m.equals("dispatchTouchEvent")) __ho23= true;
if (m.equals("onActionModeStarted")) __ho98= true;
if (m.equals("onPostCreate")) __ho137= true;
if (m.equals("hashCode")) __ho87= true;
if (m.equals("getMainLooper")) __ho65= true;
if (m.equals("getDir")) __ho54= true;
if (m.equals("deleteFile")) __ho18= true;
if (m.equals("getTaskId")) __ho78= true;
if (m.equals("navigateUpTo")) __ho95= true;
if (m.equals("revokeUriPermission")) __ho173= true;
if (m.equals("finishActivity")) __ho36= true;
if (m.equals("finishFromChild")) __ho39= true;
if (m.equals("takeKeyEvents")) __ho209= true;
if (m.equals("overridePendingTransition")) __ho165= true;
if (m.equals("checkCallingPermission")) __ho5= true;
if (m.equals("enforceCallingPermission")) __ho28= true;
if (m.equals("unregisterForContextMenu")) __ho214= true;
if (m.equals("findViewById")) __ho34= true;
if (m.equals("onNavigateUp")) __ho130= true;
if (m.equals("enforceCallingOrSelfPermission")) __ho26= true;
if (m.equals("removeStickyBroadcastAsUser")) __ho172= true;
if (m.equals("onNavigateUpFromChild")) __ho131= true;
if (m.equals("isTaskRoot")) __ho93= true;
if (m.equals("getContentResolver")) __ho51= true;
if (m.equals("getPackageResourcePath")) __ho71= true;
if (m.equals("isFinishing")) __ho91= true;
if (m.equals("getIntent")) __ho60= true;
if (m.equals("onStop")) __ho150= true;
if (m.equals("onWindowStartingActionMode")) __ho159= true;
if (m.equals("enforceCallingOrSelfUriPermission")) __ho27= true;
if (m.equals("getDatabasePath")) __ho53= true;
if (m.equals("startActivityIfNeeded")) __ho198= true;
if (m.equals("getCacheDir")) __ho45= true;
if (m.equals("getTheme")) __ho79= true;
if (m.equals("checkCallingOrSelfPermission")) __ho3= true;
if (m.equals("setTheme")) __ho186= true;
if (m.equals("sendOrderedBroadcastAsUser")) __ho177= true;
if (m.equals("onCreatePanelMenu")) __ho115= true;
if (m.equals("onPostResume")) __ho138= true;
if (m.equals("bindService")) __ho2= true;
if (m.equals("isRestricted")) __ho92= true;
if (m.equals("onPreparePanel")) __ho142= true;
if (m.equals("checkCallingUriPermission")) __ho6= true;
if (m.equals("getSystemService")) __ho77= true;
if (m.equals("startSearch")) __ho205= true;
if (m.equals("getPackageCodePath")) __ho68= true;
if (m.equals("onContextItemSelected")) __ho107= true;
if (m.equals("onApplyThemeResource")) __ho100= true;
if (m.equals("onPause")) __ho136= true;
if (m.equals("finishActivityFromChild")) __ho37= true;
if (m.equals("startActivity")) __ho194= true;
if (m.equals("getLayoutInflater")) __ho62= true;
if (m.equals("startActionMode")) __ho192= true;
if (m.equals("grantUriPermission")) __ho85= true;
if (m.equals("onRetainNonConfigurationInstance")) __ho146= true;
if (m.equals("getAssets")) __ho43= true;
if (m.equals("onDestroy")) __ho119= true;
if (m.equals("onKeyUp")) __ho126= true;
if (m.equals("onMenuOpened")) __ho129= true;
if (m.equals("getExternalFilesDir")) __ho56= true;
if (m.equals("startManagingCursor")) __ho203= true;
if (m.equals("onPrepareDialog")) __ho139= true;
if (m.equals("openContextMenu")) __ho160= true;
if (m.equals("getCallingPackage")) __ho47= true;
if (m.equals("equals")) __ho32= true;
if (m.equals("onAttachFragment")) __ho101= true;
if (m.equals("hasWindowFocus")) __ho86= true;
if (m.equals("onSaveInstanceState")) __ho147= true;
if (m.equals("onCreateOptionsMenu")) __ho114= true;
if (m.equals("registerComponentCallbacks")) __ho168= true;
if (m.equals("sendOrderedBroadcast")) __ho176= true;
if (m.equals("sendBroadcastAsUser")) __ho175= true;
if (m.equals("getExternalCacheDir")) __ho55= true;
if (m.equals("startIntentSenderForResult")) __ho201= true;
if (m.equals("onLowMemory")) __ho127= true;
if (m.equals("onOptionsItemSelected")) __ho133= true;
if (m.equals("onCreateThumbnail")) __ho117= true;
if (m.equals("onStart")) __ho149= true;
if (m.equals("startNextMatchingActivity")) __ho204= true;
if (m.equals("onUserInteraction")) __ho155= true;
if (m.equals("onTrackballEvent")) __ho153= true;
if (m.equals("onTouchEvent")) __ho152= true;
if (m.equals("onUserLeaveHint")) __ho156= true;
if (m.equals("onResume")) __ho145= true;
if (m.equals("getPreferences")) __ho73= true;
if (m.equals("startService")) __ho206= true;
if (m.equals("onContextMenuClosed")) __ho108= true;
if (m.equals("registerReceiver")) __ho170= true;
if (m.equals("getPackageManager")) __ho69= true;
if (m.equals("onCreateView")) __ho118= true;
if (m.equals("onConfigurationChanged")) __ho105= true;
if (m.equals("onContentChanged")) __ho106= true;
if (m.equals("onCreateContextMenu")) __ho110= true;
if (m.equals("onPrepareNavigateUpTaskStack")) __ho140= true;
if (m.equals("getLastNonConfigurationInstance")) __ho61= true;
if (m.equals("onKeyDown")) __ho122= true;
if (m.equals("sendBroadcast")) __ho174= true;
if (m.equals("unbindService")) __ho212= true;
if (m.equals("createPendingResult")) __ho15= true;
if (m.equals("getBaseContext")) __ho44= true;
if (m.equals("registerForContextMenu")) __ho169= true;
if (m.equals("enforcePermission")) __ho30= true;
if (m.equals("checkUriPermission")) __ho8= true;
if (m.equals("dump")) __ho25= true;
if (m.equals("startIntentSenderFromChild")) __ho202= true;
if (m.equals("onCreate")) __ho109= true;
if (m.equals("clearWallpaper")) __ho9= true;
if (m.equals("onWindowFocusChanged")) __ho158= true;
if (m.equals("startActivityFromChild")) __ho196= true;
if (m.equals("onMenuItemSelected")) __ho128= true;
if (m.equals("onCreateDescription")) __ho111= true;
if (m.equals("getApplicationInfo")) __ho42= true;
if (m.equals("setContentView")) __ho182= true;
if (m.equals("unregisterReceiver")) __ho215= true;
if (m.equals("stopService")) __ho208= true;
if (m.equals("onDetachedFromWindow")) __ho120= true;
}
}
private boolean __ho0;
private boolean __ho1;
private boolean __ho2;
private boolean __ho3;
private boolean __ho4;
private boolean __ho5;
private boolean __ho6;
private boolean __ho7;
private boolean __ho8;
private boolean __ho9;
private boolean __ho10;
private boolean __ho11;
private boolean __ho12;
private boolean __ho13;
private boolean __ho14;
private boolean __ho15;
private boolean __ho16;
private boolean __ho17;
private boolean __ho18;
private boolean __ho19;
private boolean __ho20;
private boolean __ho21;
private boolean __ho22;
private boolean __ho23;
private boolean __ho24;
private boolean __ho25;
private boolean __ho26;
private boolean __ho27;
private boolean __ho28;
private boolean __ho29;
private boolean __ho30;
private boolean __ho31;
private boolean __ho32;
private boolean __ho33;
private boolean __ho34;
private boolean __ho35;
private boolean __ho36;
private boolean __ho37;
private boolean __ho38;
private boolean __ho39;
private boolean __ho40;
private boolean __ho41;
private boolean __ho42;
private boolean __ho43;
private boolean __ho44;
private boolean __ho45;
private boolean __ho46;
private boolean __ho47;
private boolean __ho48;
private boolean __ho49;
private boolean __ho50;
private boolean __ho51;
private boolean __ho52;
private boolean __ho53;
private boolean __ho54;
private boolean __ho55;
private boolean __ho56;
private boolean __ho57;
private boolean __ho58;
private boolean __ho59;
private boolean __ho60;
private boolean __ho61;
private boolean __ho62;
private boolean __ho63;
private boolean __ho64;
private boolean __ho65;
private boolean __ho66;
private boolean __ho67;
private boolean __ho68;
private boolean __ho69;
private boolean __ho70;
private boolean __ho71;
private boolean __ho72;
private boolean __ho73;
private boolean __ho74;
private boolean __ho75;
private boolean __ho76;
private boolean __ho77;
private boolean __ho78;
private boolean __ho79;
private boolean __ho80;
private boolean __ho81;
private boolean __ho82;
private boolean __ho83;
private boolean __ho84;
private boolean __ho85;
private boolean __ho86;
private boolean __ho87;
private boolean __ho88;
private boolean __ho89;
private boolean __ho90;
private boolean __ho91;
private boolean __ho92;
private boolean __ho93;
private boolean __ho94;
private boolean __ho95;
private boolean __ho96;
private boolean __ho97;
private boolean __ho98;
private boolean __ho99;
private boolean __ho100;
private boolean __ho101;
private boolean __ho102;
private boolean __ho103;
private boolean __ho104;
private boolean __ho105;
private boolean __ho106;
private boolean __ho107;
private boolean __ho108;
private boolean __ho109;
private boolean __ho110;
private boolean __ho111;
private boolean __ho112;
private boolean __ho113;
private boolean __ho114;
private boolean __ho115;
private boolean __ho116;
private boolean __ho117;
private boolean __ho118;
private boolean __ho119;
private boolean __ho120;
private boolean __ho121;
private boolean __ho122;
private boolean __ho123;
private boolean __ho124;
private boolean __ho125;
private boolean __ho126;
private boolean __ho127;
private boolean __ho128;
private boolean __ho129;
private boolean __ho130;
private boolean __ho131;
private boolean __ho132;
private boolean __ho133;
private boolean __ho134;
private boolean __ho135;
private boolean __ho136;
private boolean __ho137;
private boolean __ho138;
private boolean __ho139;
private boolean __ho140;
private boolean __ho141;
private boolean __ho142;
private boolean __ho143;
private boolean __ho144;
private boolean __ho145;
private boolean __ho146;
private boolean __ho147;
private boolean __ho148;
private boolean __ho149;
private boolean __ho150;
private boolean __ho151;
private boolean __ho152;
private boolean __ho153;
private boolean __ho154;
private boolean __ho155;
private boolean __ho156;
private boolean __ho157;
private boolean __ho158;
private boolean __ho159;
private boolean __ho160;
private boolean __ho161;
private boolean __ho162;
private boolean __ho163;
private boolean __ho164;
private boolean __ho165;
private boolean __ho166;
private boolean __ho167;
private boolean __ho168;
private boolean __ho169;
private boolean __ho170;
private boolean __ho171;
private boolean __ho172;
private boolean __ho173;
private boolean __ho174;
private boolean __ho175;
private boolean __ho176;
private boolean __ho177;
private boolean __ho178;
private boolean __ho179;
private boolean __ho180;
private boolean __ho181;
private boolean __ho182;
private boolean __ho183;
private boolean __ho184;
private boolean __ho185;
private boolean __ho186;
private boolean __ho187;
private boolean __ho188;
private boolean __ho189;
private boolean __ho190;
private boolean __ho191;
private boolean __ho192;
private boolean __ho193;
private boolean __ho194;
private boolean __ho195;
private boolean __ho196;
private boolean __ho197;
private boolean __ho198;
private boolean __ho199;
private boolean __ho200;
private boolean __ho201;
private boolean __ho202;
private boolean __ho203;
private boolean __ho204;
private boolean __ho205;
private boolean __ho206;
private boolean __ho207;
private boolean __ho208;
private boolean __ho209;
private boolean __ho210;
private boolean __ho211;
private boolean __ho212;
private boolean __ho213;
private boolean __ho214;
private boolean __ho215;
}
| fixed nativescript activity so it passes every method return type
| src/src/com/tns/NativeScriptActivity.java | fixed nativescript activity so it passes every method return type | <ide><path>rc/src/com/tns/NativeScriptActivity.java
<ide> com.tns.Platform.initInstance(this);
<ide> objectId = com.tns.Platform.getorCreateJavaObjectID(this);
<ide> }
<del>
<add>
<ide> public void addContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
<ide> {
<ide> if (__ho0)
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "addContentView", args);
<add> com.tns.Platform.callJSMethod(this, "addContentView", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "applyOverrideConfiguration", args);
<add> com.tns.Platform.callJSMethod(this, "applyOverrideConfiguration", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "bindService", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "bindService", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfUriPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkCallingOrSelfUriPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkCallingPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkCallingUriPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkCallingUriPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> return super.checkPermission(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public int checkUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3)
<del> {
<del> if (__ho8)
<del> {
<del> Object[] args = new Object[4];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkUriPermission", args);
<del> }
<del> else
<del> {
<del> return super.checkUriPermission(param_0, param_1, param_2, param_3);
<ide> }
<ide> }
<ide>
<ide> args[3] = param_3;
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "checkUriPermission", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "checkUriPermission", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<add> public int checkUriPermission(android.net.Uri param_0, int param_1, int param_2, int param_3)
<add> {
<add> if (__ho8)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> return (int)com.tns.Platform.callJSMethod(this, "checkUriPermission", int.class, args);
<add> }
<add> else
<add> {
<add> return super.checkUriPermission(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<ide> public void clearWallpaper() throws java.io.IOException
<ide> {
<ide> if (__ho9)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "clearWallpaper", args);
<add> com.tns.Platform.callJSMethod(this, "clearWallpaper", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho10)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "closeContextMenu", args);
<add> com.tns.Platform.callJSMethod(this, "closeContextMenu", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho11)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "closeOptionsMenu", args);
<add> com.tns.Platform.callJSMethod(this, "closeOptionsMenu", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createConfigurationContext", args);
<add> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createConfigurationContext", android.content.Context.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createDisplayContext", args);
<add> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createDisplayContext", android.content.Context.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createPackageContext", args);
<add> return (android.content.Context)com.tns.Platform.callJSMethod(this, "createPackageContext", android.content.Context.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> return (android.app.PendingIntent)com.tns.Platform.callJSMethod(this, "createPendingResult", args);
<add> return (android.app.PendingIntent)com.tns.Platform.callJSMethod(this, "createPendingResult", android.app.PendingIntent.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho16)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String[])com.tns.Platform.callJSMethod(this, "databaseList", args);
<add> return (java.lang.String[])com.tns.Platform.callJSMethod(this, "databaseList", java.lang.String[].class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "deleteDatabase", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "deleteDatabase", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "deleteFile", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "deleteFile", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchGenericMotionEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchGenericMotionEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyShortcutEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchKeyShortcutEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchPopulateAccessibilityEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchPopulateAccessibilityEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchTouchEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchTouchEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "dispatchTrackballEvent", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "dispatchTrackballEvent", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<ide> args[3] = param_3;
<del> com.tns.Platform.callJSMethod(this, "dump", args);
<add> com.tns.Platform.callJSMethod(this, "dump", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfUriPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceCallingOrSelfUriPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "enforceCallingPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceCallingPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "enforceCallingUriPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceCallingUriPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<ide> args[3] = param_3;
<del> com.tns.Platform.callJSMethod(this, "enforcePermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforcePermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<del> com.tns.Platform.callJSMethod(this, "enforceUriPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceUriPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[2] = param_2;
<ide> args[3] = param_3;
<ide> args[4] = param_4;
<del> com.tns.Platform.callJSMethod(this, "enforceUriPermission", args);
<add> com.tns.Platform.callJSMethod(this, "enforceUriPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "equals", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "equals", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho33)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String[])com.tns.Platform.callJSMethod(this, "fileList", args);
<add> return (java.lang.String[])com.tns.Platform.callJSMethod(this, "fileList", java.lang.String[].class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.view.View)com.tns.Platform.callJSMethod(this, "findViewById", args);
<add> return (android.view.View)com.tns.Platform.callJSMethod(this, "findViewById", android.view.View.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho35)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "finish", args);
<add> com.tns.Platform.callJSMethod(this, "finish", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "finishActivity", args);
<add> com.tns.Platform.callJSMethod(this, "finishActivity", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "finishActivityFromChild", args);
<add> com.tns.Platform.callJSMethod(this, "finishActivityFromChild", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho38)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "finishAffinity", args);
<add> com.tns.Platform.callJSMethod(this, "finishAffinity", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "finishFromChild", args);
<add> com.tns.Platform.callJSMethod(this, "finishFromChild", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho40)
<ide> {
<ide> Object[] args = null;
<del> return (android.app.ActionBar)com.tns.Platform.callJSMethod(this, "getActionBar", args);
<add> return (android.app.ActionBar)com.tns.Platform.callJSMethod(this, "getActionBar", android.app.ActionBar.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho41)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.Context)com.tns.Platform.callJSMethod(this, "getApplicationContext", args);
<add> return (android.content.Context)com.tns.Platform.callJSMethod(this, "getApplicationContext", android.content.Context.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho42)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.pm.ApplicationInfo)com.tns.Platform.callJSMethod(this, "getApplicationInfo", args);
<add> return (android.content.pm.ApplicationInfo)com.tns.Platform.callJSMethod(this, "getApplicationInfo", android.content.pm.ApplicationInfo.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho43)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.res.AssetManager)com.tns.Platform.callJSMethod(this, "getAssets", args);
<add> return (android.content.res.AssetManager)com.tns.Platform.callJSMethod(this, "getAssets", android.content.res.AssetManager.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho44)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.Context)com.tns.Platform.callJSMethod(this, "getBaseContext", args);
<add> return (android.content.Context)com.tns.Platform.callJSMethod(this, "getBaseContext", android.content.Context.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho45)
<ide> {
<ide> Object[] args = null;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getCacheDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getCacheDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho46)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getCallingActivity", args);
<add> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getCallingActivity", android.content.ComponentName.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho47)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getCallingPackage", args);
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getCallingPackage", java.lang.String.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho48)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "getChangingConfigurations", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "getChangingConfigurations", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho49)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.ClassLoader)com.tns.Platform.callJSMethod(this, "getClassLoader", args);
<add> return (java.lang.ClassLoader)com.tns.Platform.callJSMethod(this, "getClassLoader", java.lang.ClassLoader.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho50)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getComponentName", args);
<add> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "getComponentName", android.content.ComponentName.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho51)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.ContentResolver)com.tns.Platform.callJSMethod(this, "getContentResolver", args);
<add> return (android.content.ContentResolver)com.tns.Platform.callJSMethod(this, "getContentResolver", android.content.ContentResolver.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho52)
<ide> {
<ide> Object[] args = null;
<del> return (android.view.View)com.tns.Platform.callJSMethod(this, "getCurrentFocus", args);
<add> return (android.view.View)com.tns.Platform.callJSMethod(this, "getCurrentFocus", android.view.View.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getDatabasePath", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getDatabasePath", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho55)
<ide> {
<ide> Object[] args = null;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalCacheDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalCacheDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalFilesDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getExternalFilesDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getFileStreamPath", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getFileStreamPath", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho58)
<ide> {
<ide> Object[] args = null;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getFilesDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getFilesDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho59)
<ide> {
<ide> Object[] args = null;
<del> return (android.app.FragmentManager)com.tns.Platform.callJSMethod(this, "getFragmentManager", args);
<add> return (android.app.FragmentManager)com.tns.Platform.callJSMethod(this, "getFragmentManager", android.app.FragmentManager.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho60)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getIntent", args);
<add> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getIntent", android.content.Intent.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho61)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getLastNonConfigurationInstance", args);
<add> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getLastNonConfigurationInstance", java.lang.Object.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho62)
<ide> {
<ide> Object[] args = null;
<del> return (android.view.LayoutInflater)com.tns.Platform.callJSMethod(this, "getLayoutInflater", args);
<add> return (android.view.LayoutInflater)com.tns.Platform.callJSMethod(this, "getLayoutInflater", android.view.LayoutInflater.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho63)
<ide> {
<ide> Object[] args = null;
<del> return (android.app.LoaderManager)com.tns.Platform.callJSMethod(this, "getLoaderManager", args);
<add> return (android.app.LoaderManager)com.tns.Platform.callJSMethod(this, "getLoaderManager", android.app.LoaderManager.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho64)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getLocalClassName", args);
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getLocalClassName", java.lang.String.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho65)
<ide> {
<ide> Object[] args = null;
<del> return (android.os.Looper)com.tns.Platform.callJSMethod(this, "getMainLooper", args);
<add> return (android.os.Looper)com.tns.Platform.callJSMethod(this, "getMainLooper", android.os.Looper.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho66)
<ide> {
<ide> Object[] args = null;
<del> return (android.view.MenuInflater)com.tns.Platform.callJSMethod(this, "getMenuInflater", args);
<add> return (android.view.MenuInflater)com.tns.Platform.callJSMethod(this, "getMenuInflater", android.view.MenuInflater.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho67)
<ide> {
<ide> Object[] args = null;
<del> return (java.io.File)com.tns.Platform.callJSMethod(this, "getObbDir", args);
<add> return (java.io.File)com.tns.Platform.callJSMethod(this, "getObbDir", java.io.File.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho68)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageCodePath", args);
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageCodePath", java.lang.String.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho69)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.pm.PackageManager)com.tns.Platform.callJSMethod(this, "getPackageManager", args);
<add> return (android.content.pm.PackageManager)com.tns.Platform.callJSMethod(this, "getPackageManager", android.content.pm.PackageManager.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho70)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageName", args);
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageName", java.lang.String.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho71)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageResourcePath", args);
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "getPackageResourcePath", java.lang.String.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho72)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getParentActivityIntent", args);
<add> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "getParentActivityIntent", android.content.Intent.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getPreferences", args);
<add> return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getPreferences", android.content.SharedPreferences.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho74)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "getRequestedOrientation", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "getRequestedOrientation", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho75)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.res.Resources)com.tns.Platform.callJSMethod(this, "getResources", args);
<add> return (android.content.res.Resources)com.tns.Platform.callJSMethod(this, "getResources", android.content.res.Resources.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getSharedPreferences", args);
<add> return (android.content.SharedPreferences)com.tns.Platform.callJSMethod(this, "getSharedPreferences", android.content.SharedPreferences.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getSystemService", args);
<add> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "getSystemService", java.lang.Object.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho78)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "getTaskId", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "getTaskId", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho79)
<ide> {
<ide> Object[] args = null;
<del> return (android.content.res.Resources.Theme)com.tns.Platform.callJSMethod(this, "getTheme", args);
<add> return (android.content.res.Resources.Theme)com.tns.Platform.callJSMethod(this, "getTheme", android.content.res.Resources.Theme.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho80)
<ide> {
<ide> Object[] args = null;
<del> return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "getWallpaper", args);
<add> return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "getWallpaper", android.graphics.drawable.Drawable.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho81)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumHeight", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumHeight", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho82)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumWidth", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "getWallpaperDesiredMinimumWidth", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho83)
<ide> {
<ide> Object[] args = null;
<del> return (android.view.Window)com.tns.Platform.callJSMethod(this, "getWindow", args);
<add> return (android.view.Window)com.tns.Platform.callJSMethod(this, "getWindow", android.view.Window.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho84)
<ide> {
<ide> Object[] args = null;
<del> return (android.view.WindowManager)com.tns.Platform.callJSMethod(this, "getWindowManager", args);
<add> return (android.view.WindowManager)com.tns.Platform.callJSMethod(this, "getWindowManager", android.view.WindowManager.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "grantUriPermission", args);
<add> com.tns.Platform.callJSMethod(this, "grantUriPermission", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho86)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "hasWindowFocus", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "hasWindowFocus", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho87)
<ide> {
<ide> Object[] args = null;
<del> return (Integer)com.tns.Platform.callJSMethod(this, "hashCode", args);
<add> return (int)com.tns.Platform.callJSMethod(this, "hashCode", int.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho88)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "invalidateOptionsMenu", args);
<add> com.tns.Platform.callJSMethod(this, "invalidateOptionsMenu", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho89)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "isChangingConfigurations", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "isChangingConfigurations", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho90)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "isDestroyed", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "isDestroyed", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho91)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "isFinishing", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "isFinishing", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho92)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "isRestricted", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "isRestricted", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho93)
<ide> {
<ide> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "isTaskRoot", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "isTaskRoot", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "moveTaskToBack", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "moveTaskToBack", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "navigateUpTo", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "navigateUpTo", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "navigateUpToFromChild", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "navigateUpToFromChild", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onActionModeFinished", args);
<add> com.tns.Platform.callJSMethod(this, "onActionModeFinished", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onActionModeStarted", args);
<add> com.tns.Platform.callJSMethod(this, "onActionModeStarted", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "onActivityResult", args);
<add> com.tns.Platform.callJSMethod(this, "onActivityResult", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "onApplyThemeResource", args);
<add> com.tns.Platform.callJSMethod(this, "onApplyThemeResource", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onAttachFragment", args);
<add> com.tns.Platform.callJSMethod(this, "onAttachFragment", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho102)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onAttachedToWindow", args);
<add> com.tns.Platform.callJSMethod(this, "onAttachedToWindow", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho103)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onBackPressed", args);
<add> com.tns.Platform.callJSMethod(this, "onBackPressed", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "onChildTitleChanged", args);
<add> com.tns.Platform.callJSMethod(this, "onChildTitleChanged", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onConfigurationChanged", args);
<add> com.tns.Platform.callJSMethod(this, "onConfigurationChanged", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho106)
<ide> {
<ide> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onContentChanged", args);
<add> com.tns.Platform.callJSMethod(this, "onContentChanged", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onContextItemSelected", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onContextItemSelected", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onContextMenuClosed", args);
<add> com.tns.Platform.callJSMethod(this, "onContextMenuClosed", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onCreate", args);
<add> com.tns.Platform.callJSMethod(this, "onCreate", void.class, args);
<ide> android.util.Log.d(com.tns.Platform.DEFAULT_LOG_TAG, "NativeScriptActivity.onCreate called");
<ide> }
<ide> else
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "onCreateContextMenu", args);
<add> com.tns.Platform.callJSMethod(this, "onCreateContextMenu", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> if (__ho111)
<ide> {
<ide> Object[] args = null;
<del> return (java.lang.CharSequence)com.tns.Platform.callJSMethod(this, "onCreateDescription", args);
<add> return (java.lang.CharSequence)com.tns.Platform.callJSMethod(this, "onCreateDescription", java.lang.CharSequence.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", args);
<add> return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", android.app.Dialog.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", args);
<add> return (android.app.Dialog)com.tns.Platform.callJSMethod(this, "onCreateDialog", android.app.Dialog.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onCreateNavigateUpTaskStack", args);
<add> com.tns.Platform.callJSMethod(this, "onCreateNavigateUpTaskStack", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onCreateOptionsMenu", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onCreateOptionsMenu", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onCreatePanelMenu", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onCreatePanelMenu", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreatePanelView", args);
<add> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreatePanelView", android.view.View.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onCreateThumbnail", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onCreateThumbnail", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<add> public android.view.View onCreateView(android.view.View param_0, java.lang.String param_1, android.content.Context param_2, android.util.AttributeSet param_3)
<add> {
<add> if (__ho118)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", android.view.View.class, args);
<add> }
<add> else
<add> {
<add> return super.onCreateView(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<ide> public android.view.View onCreateView(java.lang.String param_0, android.content.Context param_1, android.util.AttributeSet param_2)
<ide> {
<ide> if (__ho118)
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", args);
<add> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", android.view.View.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<del> public android.view.View onCreateView(android.view.View param_0, java.lang.String param_1, android.content.Context param_2, android.util.AttributeSet param_3)
<del> {
<del> if (__ho118)
<add> protected void onDestroy()
<add> {
<add> if (__ho119)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onDestroy", void.class, args);
<add> }
<add> else
<add> {
<add> super.onDestroy();
<add> }
<add> // TODO: remove from com.tns.Platform.strongInstances
<add> }
<add>
<add> public void onDetachedFromWindow()
<add> {
<add> if (__ho120)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onDetachedFromWindow", void.class, args);
<add> }
<add> else
<add> {
<add> super.onDetachedFromWindow();
<add> }
<add> }
<add>
<add> public boolean onGenericMotionEvent(android.view.MotionEvent param_0)
<add> {
<add> if (__ho121)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onGenericMotionEvent", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onGenericMotionEvent(param_0);
<add> }
<add> }
<add>
<add> public boolean onKeyDown(int param_0, android.view.KeyEvent param_1)
<add> {
<add> if (__ho122)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onKeyDown", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onKeyDown(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onKeyLongPress(int param_0, android.view.KeyEvent param_1)
<add> {
<add> if (__ho123)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onKeyLongPress", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onKeyLongPress(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onKeyMultiple(int param_0, int param_1, android.view.KeyEvent param_2)
<add> {
<add> if (__ho124)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onKeyMultiple", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onKeyMultiple(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public boolean onKeyShortcut(int param_0, android.view.KeyEvent param_1)
<add> {
<add> if (__ho125)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onKeyShortcut", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onKeyShortcut(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onKeyUp(int param_0, android.view.KeyEvent param_1)
<add> {
<add> if (__ho126)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onKeyUp", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onKeyUp(param_0, param_1);
<add> }
<add> }
<add>
<add> public void onLowMemory()
<add> {
<add> if (__ho127)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onLowMemory", void.class, args);
<add> }
<add> else
<add> {
<add> super.onLowMemory();
<add> }
<add> }
<add>
<add> public boolean onMenuItemSelected(int param_0, android.view.MenuItem param_1)
<add> {
<add> if (__ho128)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onMenuItemSelected", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onMenuItemSelected(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onMenuOpened(int param_0, android.view.Menu param_1)
<add> {
<add> if (__ho129)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onMenuOpened", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onMenuOpened(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onNavigateUp()
<add> {
<add> if (__ho130)
<add> {
<add> Object[] args = null;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onNavigateUp", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onNavigateUp();
<add> }
<add> }
<add>
<add> public boolean onNavigateUpFromChild(android.app.Activity param_0)
<add> {
<add> if (__ho131)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onNavigateUpFromChild", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onNavigateUpFromChild(param_0);
<add> }
<add> }
<add>
<add> protected void onNewIntent(android.content.Intent param_0)
<add> {
<add> if (__ho132)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onNewIntent", void.class, args);
<add> }
<add> else
<add> {
<add> super.onNewIntent(param_0);
<add> }
<add> }
<add>
<add> public boolean onOptionsItemSelected(android.view.MenuItem param_0)
<add> {
<add> if (__ho133)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onOptionsItemSelected", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onOptionsItemSelected(param_0);
<add> }
<add> }
<add>
<add> public void onOptionsMenuClosed(android.view.Menu param_0)
<add> {
<add> if (__ho134)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onOptionsMenuClosed", void.class, args);
<add> }
<add> else
<add> {
<add> super.onOptionsMenuClosed(param_0);
<add> }
<add> }
<add>
<add> public void onPanelClosed(int param_0, android.view.Menu param_1)
<add> {
<add> if (__ho135)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "onPanelClosed", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPanelClosed(param_0, param_1);
<add> }
<add> }
<add>
<add> protected void onPause()
<add> {
<add> if (__ho136)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onPause", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPause();
<add> }
<add> }
<add>
<add> protected void onPostCreate(android.os.Bundle param_0)
<add> {
<add> if (__ho137)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onPostCreate", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPostCreate(param_0);
<add> }
<add> }
<add>
<add> protected void onPostResume()
<add> {
<add> if (__ho138)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onPostResume", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPostResume();
<add> }
<add> }
<add>
<add> protected void onPrepareDialog(int param_0, android.app.Dialog param_1)
<add> {
<add> if (__ho139)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "onPrepareDialog", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPrepareDialog(param_0, param_1);
<add> }
<add> }
<add>
<add> protected void onPrepareDialog(int param_0, android.app.Dialog param_1, android.os.Bundle param_2)
<add> {
<add> if (__ho139)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> com.tns.Platform.callJSMethod(this, "onPrepareDialog", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPrepareDialog(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
<add> {
<add> if (__ho140)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onPrepareNavigateUpTaskStack", void.class, args);
<add> }
<add> else
<add> {
<add> super.onPrepareNavigateUpTaskStack(param_0);
<add> }
<add> }
<add>
<add> public boolean onPrepareOptionsMenu(android.view.Menu param_0)
<add> {
<add> if (__ho141)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onPrepareOptionsMenu", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onPrepareOptionsMenu(param_0);
<add> }
<add> }
<add>
<add> public boolean onPreparePanel(int param_0, android.view.View param_1, android.view.Menu param_2)
<add> {
<add> if (__ho142)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onPreparePanel", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onPreparePanel(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> protected void onRestart()
<add> {
<add> if (__ho143)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onRestart", void.class, args);
<add> }
<add> else
<add> {
<add> super.onRestart();
<add> }
<add> }
<add>
<add> protected void onRestoreInstanceState(android.os.Bundle param_0)
<add> {
<add> if (__ho144)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onRestoreInstanceState", void.class, args);
<add> }
<add> else
<add> {
<add> super.onRestoreInstanceState(param_0);
<add> }
<add> }
<add>
<add> protected void onResume()
<add> {
<add> if (__ho145)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onResume", void.class, args);
<add> }
<add> else
<add> {
<add> super.onResume();
<add> }
<add> }
<add>
<add> public java.lang.Object onRetainNonConfigurationInstance()
<add> {
<add> if (__ho146)
<add> {
<add> Object[] args = null;
<add> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "onRetainNonConfigurationInstance", java.lang.Object.class, args);
<add> }
<add> else
<add> {
<add> return super.onRetainNonConfigurationInstance();
<add> }
<add> }
<add>
<add> protected void onSaveInstanceState(android.os.Bundle param_0)
<add> {
<add> if (__ho147)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onSaveInstanceState", void.class, args);
<add> }
<add> else
<add> {
<add> super.onSaveInstanceState(param_0);
<add> }
<add> }
<add>
<add> public boolean onSearchRequested()
<add> {
<add> if (__ho148)
<add> {
<add> Object[] args = null;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onSearchRequested", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onSearchRequested();
<add> }
<add> }
<add>
<add> protected void onStart()
<add> {
<add> if (__ho149)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onStart", void.class, args);
<add> }
<add> else
<add> {
<add> super.onStart();
<add> }
<add> }
<add>
<add> protected void onStop()
<add> {
<add> if (__ho150)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onStop", void.class, args);
<add> }
<add> else
<add> {
<add> super.onStop();
<add> }
<add> }
<add>
<add> protected void onTitleChanged(java.lang.CharSequence param_0, int param_1)
<add> {
<add> if (__ho151)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "onTitleChanged", void.class, args);
<add> }
<add> else
<add> {
<add> super.onTitleChanged(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean onTouchEvent(android.view.MotionEvent param_0)
<add> {
<add> if (__ho152)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onTouchEvent", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onTouchEvent(param_0);
<add> }
<add> }
<add>
<add> public boolean onTrackballEvent(android.view.MotionEvent param_0)
<add> {
<add> if (__ho153)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "onTrackballEvent", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.onTrackballEvent(param_0);
<add> }
<add> }
<add>
<add> public void onTrimMemory(int param_0)
<add> {
<add> if (__ho154)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onTrimMemory", void.class, args);
<add> }
<add> else
<add> {
<add> super.onTrimMemory(param_0);
<add> }
<add> }
<add>
<add> public void onUserInteraction()
<add> {
<add> if (__ho155)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onUserInteraction", void.class, args);
<add> }
<add> else
<add> {
<add> super.onUserInteraction();
<add> }
<add> }
<add>
<add> protected void onUserLeaveHint()
<add> {
<add> if (__ho156)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "onUserLeaveHint", void.class, args);
<add> }
<add> else
<add> {
<add> super.onUserLeaveHint();
<add> }
<add> }
<add>
<add> public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams param_0)
<add> {
<add> if (__ho157)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onWindowAttributesChanged", void.class, args);
<add> }
<add> else
<add> {
<add> super.onWindowAttributesChanged(param_0);
<add> }
<add> }
<add>
<add> public void onWindowFocusChanged(boolean param_0)
<add> {
<add> if (__ho158)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "onWindowFocusChanged", void.class, args);
<add> }
<add> else
<add> {
<add> super.onWindowFocusChanged(param_0);
<add> }
<add> }
<add>
<add> public android.view.ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback param_0)
<add> {
<add> if (__ho159)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "onWindowStartingActionMode", android.view.ActionMode.class, args);
<add> }
<add> else
<add> {
<add> return super.onWindowStartingActionMode(param_0);
<add> }
<add> }
<add>
<add> public void openContextMenu(android.view.View param_0)
<add> {
<add> if (__ho160)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "openContextMenu", void.class, args);
<add> }
<add> else
<add> {
<add> super.openContextMenu(param_0);
<add> }
<add> }
<add>
<add> public java.io.FileInputStream openFileInput(java.lang.String param_0) throws java.io.FileNotFoundException
<add> {
<add> if (__ho161)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (java.io.FileInputStream)com.tns.Platform.callJSMethod(this, "openFileInput", java.io.FileInputStream.class, args);
<add> }
<add> else
<add> {
<add> return super.openFileInput(param_0);
<add> }
<add> }
<add>
<add> public java.io.FileOutputStream openFileOutput(java.lang.String param_0, int param_1) throws java.io.FileNotFoundException
<add> {
<add> if (__ho162)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (java.io.FileOutputStream)com.tns.Platform.callJSMethod(this, "openFileOutput", java.io.FileOutputStream.class, args);
<add> }
<add> else
<add> {
<add> return super.openFileOutput(param_0, param_1);
<add> }
<add> }
<add>
<add> public void openOptionsMenu()
<add> {
<add> if (__ho163)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "openOptionsMenu", void.class, args);
<add> }
<add> else
<add> {
<add> super.openOptionsMenu();
<add> }
<add> }
<add>
<add> public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2, android.database.DatabaseErrorHandler param_3)
<add> {
<add> if (__ho164)
<ide> {
<ide> Object[] args = new Object[4];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<ide> args[3] = param_3;
<del> return (android.view.View)com.tns.Platform.callJSMethod(this, "onCreateView", args);
<del> }
<del> else
<del> {
<del> return super.onCreateView(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> protected void onDestroy()
<del> {
<del> if (__ho119)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onDestroy", args);
<del> }
<del> else
<del> {
<del> super.onDestroy();
<del> }
<del> // TODO: remove from com.tns.Platform.strongInstances
<del> }
<del>
<del> public void onDetachedFromWindow()
<del> {
<del> if (__ho120)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onDetachedFromWindow", args);
<del> }
<del> else
<del> {
<del> super.onDetachedFromWindow();
<del> }
<del> }
<del>
<del> public boolean onGenericMotionEvent(android.view.MotionEvent param_0)
<del> {
<del> if (__ho121)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onGenericMotionEvent", args);
<del> }
<del> else
<del> {
<del> return super.onGenericMotionEvent(param_0);
<del> }
<del> }
<del>
<del> public boolean onKeyDown(int param_0, android.view.KeyEvent param_1)
<del> {
<del> if (__ho122)
<add> return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", android.database.sqlite.SQLiteDatabase.class, args);
<add> }
<add> else
<add> {
<add> return super.openOrCreateDatabase(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<add> public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2)
<add> {
<add> if (__ho164)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", android.database.sqlite.SQLiteDatabase.class, args);
<add> }
<add> else
<add> {
<add> return super.openOrCreateDatabase(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void overridePendingTransition(int param_0, int param_1)
<add> {
<add> if (__ho165)
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyDown", args);
<del> }
<del> else
<del> {
<del> return super.onKeyDown(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onKeyLongPress(int param_0, android.view.KeyEvent param_1)
<del> {
<del> if (__ho123)
<add> com.tns.Platform.callJSMethod(this, "overridePendingTransition", void.class, args);
<add> }
<add> else
<add> {
<add> super.overridePendingTransition(param_0, param_1);
<add> }
<add> }
<add>
<add> public android.graphics.drawable.Drawable peekWallpaper()
<add> {
<add> if (__ho166)
<add> {
<add> Object[] args = null;
<add> return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "peekWallpaper", android.graphics.drawable.Drawable.class, args);
<add> }
<add> else
<add> {
<add> return super.peekWallpaper();
<add> }
<add> }
<add>
<add> public void recreate()
<add> {
<add> if (__ho167)
<add> {
<add> Object[] args = null;
<add> com.tns.Platform.callJSMethod(this, "recreate", void.class, args);
<add> }
<add> else
<add> {
<add> super.recreate();
<add> }
<add> }
<add>
<add> public void registerComponentCallbacks(android.content.ComponentCallbacks param_0)
<add> {
<add> if (__ho168)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "registerComponentCallbacks", void.class, args);
<add> }
<add> else
<add> {
<add> super.registerComponentCallbacks(param_0);
<add> }
<add> }
<add>
<add> public void registerForContextMenu(android.view.View param_0)
<add> {
<add> if (__ho169)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "registerForContextMenu", void.class, args);
<add> }
<add> else
<add> {
<add> super.registerForContextMenu(param_0);
<add> }
<add> }
<add>
<add> public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1, java.lang.String param_2, android.os.Handler param_3)
<add> {
<add> if (__ho170)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", android.content.Intent.class, args);
<add> }
<add> else
<add> {
<add> return super.registerReceiver(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<add> public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1)
<add> {
<add> if (__ho170)
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyLongPress", args);
<del> }
<del> else
<del> {
<del> return super.onKeyLongPress(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onKeyMultiple(int param_0, int param_1, android.view.KeyEvent param_2)
<del> {
<del> if (__ho124)
<add> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", android.content.Intent.class, args);
<add> }
<add> else
<add> {
<add> return super.registerReceiver(param_0, param_1);
<add> }
<add> }
<add>
<add> public void removeStickyBroadcast(android.content.Intent param_0)
<add> {
<add> if (__ho171)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "removeStickyBroadcast", void.class, args);
<add> }
<add> else
<add> {
<add> super.removeStickyBroadcast(param_0);
<add> }
<add> }
<add>
<add> public void removeStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
<add> {
<add> if (__ho172)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "removeStickyBroadcastAsUser", void.class, args);
<add> }
<add> else
<add> {
<add> super.removeStickyBroadcastAsUser(param_0, param_1);
<add> }
<add> }
<add>
<add> public void revokeUriPermission(android.net.Uri param_0, int param_1)
<add> {
<add> if (__ho173)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "revokeUriPermission", void.class, args);
<add> }
<add> else
<add> {
<add> super.revokeUriPermission(param_0, param_1);
<add> }
<add> }
<add>
<add> public void sendBroadcast(android.content.Intent param_0, java.lang.String param_1)
<add> {
<add> if (__ho174)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "sendBroadcast", void.class, args);
<add> }
<add> else
<add> {
<add> super.sendBroadcast(param_0, param_1);
<add> }
<add> }
<add>
<add> public void sendBroadcast(android.content.Intent param_0)
<add> {
<add> if (__ho174)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "sendBroadcast", void.class, args);
<add> }
<add> else
<add> {
<add> super.sendBroadcast(param_0);
<add> }
<add> }
<add>
<add> public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2)
<add> {
<add> if (__ho175)
<ide> {
<ide> Object[] args = new Object[3];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyMultiple", args);
<del> }
<del> else
<del> {
<del> return super.onKeyMultiple(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public boolean onKeyShortcut(int param_0, android.view.KeyEvent param_1)
<del> {
<del> if (__ho125)
<add> com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", void.class, args);
<add> }
<add> else
<add> {
<add> super.sendBroadcastAsUser(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
<add> {
<add> if (__ho175)
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyShortcut", args);
<del> }
<del> else
<del> {
<del> return super.onKeyShortcut(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onKeyUp(int param_0, android.view.KeyEvent param_1)
<del> {
<del> if (__ho126)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onKeyUp", args);
<del> }
<del> else
<del> {
<del> return super.onKeyUp(param_0, param_1);
<del> }
<del> }
<del>
<del> public void onLowMemory()
<del> {
<del> if (__ho127)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onLowMemory", args);
<del> }
<del> else
<del> {
<del> super.onLowMemory();
<del> }
<del> }
<del>
<del> public boolean onMenuItemSelected(int param_0, android.view.MenuItem param_1)
<del> {
<del> if (__ho128)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onMenuItemSelected", args);
<del> }
<del> else
<del> {
<del> return super.onMenuItemSelected(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onMenuOpened(int param_0, android.view.Menu param_1)
<del> {
<del> if (__ho129)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onMenuOpened", args);
<del> }
<del> else
<del> {
<del> return super.onMenuOpened(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onNavigateUp()
<del> {
<del> if (__ho130)
<del> {
<del> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onNavigateUp", args);
<del> }
<del> else
<del> {
<del> return super.onNavigateUp();
<del> }
<del> }
<del>
<del> public boolean onNavigateUpFromChild(android.app.Activity param_0)
<del> {
<del> if (__ho131)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onNavigateUpFromChild", args);
<del> }
<del> else
<del> {
<del> return super.onNavigateUpFromChild(param_0);
<del> }
<del> }
<del>
<del> protected void onNewIntent(android.content.Intent param_0)
<del> {
<del> if (__ho132)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onNewIntent", args);
<del> }
<del> else
<del> {
<del> super.onNewIntent(param_0);
<del> }
<del> }
<del>
<del> public boolean onOptionsItemSelected(android.view.MenuItem param_0)
<del> {
<del> if (__ho133)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onOptionsItemSelected", args);
<del> }
<del> else
<del> {
<del> return super.onOptionsItemSelected(param_0);
<del> }
<del> }
<del>
<del> public void onOptionsMenuClosed(android.view.Menu param_0)
<del> {
<del> if (__ho134)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onOptionsMenuClosed", args);
<del> }
<del> else
<del> {
<del> super.onOptionsMenuClosed(param_0);
<del> }
<del> }
<del>
<del> public void onPanelClosed(int param_0, android.view.Menu param_1)
<del> {
<del> if (__ho135)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "onPanelClosed", args);
<del> }
<del> else
<del> {
<del> super.onPanelClosed(param_0, param_1);
<del> }
<del> }
<del>
<del> protected void onPause()
<del> {
<del> if (__ho136)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onPause", args);
<del> }
<del> else
<del> {
<del> super.onPause();
<del> }
<del> }
<del>
<del> protected void onPostCreate(android.os.Bundle param_0)
<del> {
<del> if (__ho137)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onPostCreate", args);
<del> }
<del> else
<del> {
<del> super.onPostCreate(param_0);
<del> }
<del> }
<del>
<del> protected void onPostResume()
<del> {
<del> if (__ho138)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onPostResume", args);
<del> }
<del> else
<del> {
<del> super.onPostResume();
<del> }
<del> }
<del>
<del> protected void onPrepareDialog(int param_0, android.app.Dialog param_1)
<del> {
<del> if (__ho139)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "onPrepareDialog", args);
<del> }
<del> else
<del> {
<del> super.onPrepareDialog(param_0, param_1);
<del> }
<del> }
<del>
<del> protected void onPrepareDialog(int param_0, android.app.Dialog param_1, android.os.Bundle param_2)
<del> {
<del> if (__ho139)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "onPrepareDialog", args);
<del> }
<del> else
<del> {
<del> super.onPrepareDialog(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public void onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder param_0)
<del> {
<del> if (__ho140)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onPrepareNavigateUpTaskStack", args);
<del> }
<del> else
<del> {
<del> super.onPrepareNavigateUpTaskStack(param_0);
<del> }
<del> }
<del>
<del> public boolean onPrepareOptionsMenu(android.view.Menu param_0)
<del> {
<del> if (__ho141)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onPrepareOptionsMenu", args);
<del> }
<del> else
<del> {
<del> return super.onPrepareOptionsMenu(param_0);
<del> }
<del> }
<del>
<del> public boolean onPreparePanel(int param_0, android.view.View param_1, android.view.Menu param_2)
<del> {
<del> if (__ho142)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onPreparePanel", args);
<del> }
<del> else
<del> {
<del> return super.onPreparePanel(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> protected void onRestart()
<del> {
<del> if (__ho143)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onRestart", args);
<del> }
<del> else
<del> {
<del> super.onRestart();
<del> }
<del> }
<del>
<del> protected void onRestoreInstanceState(android.os.Bundle param_0)
<del> {
<del> if (__ho144)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onRestoreInstanceState", args);
<del> }
<del> else
<del> {
<del> super.onRestoreInstanceState(param_0);
<del> }
<del> }
<del>
<del> protected void onResume()
<del> {
<del> if (__ho145)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onResume", args);
<del> }
<del> else
<del> {
<del> super.onResume();
<del> }
<del> }
<del>
<del> public java.lang.Object onRetainNonConfigurationInstance()
<del> {
<del> if (__ho146)
<del> {
<del> Object[] args = null;
<del> return (java.lang.Object)com.tns.Platform.callJSMethod(this, "onRetainNonConfigurationInstance", args);
<del> }
<del> else
<del> {
<del> return super.onRetainNonConfigurationInstance();
<del> }
<del> }
<del>
<del> protected void onSaveInstanceState(android.os.Bundle param_0)
<del> {
<del> if (__ho147)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onSaveInstanceState", args);
<del> }
<del> else
<del> {
<del> super.onSaveInstanceState(param_0);
<del> }
<del> }
<del>
<del> public boolean onSearchRequested()
<del> {
<del> if (__ho148)
<del> {
<del> Object[] args = null;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onSearchRequested", args);
<del> }
<del> else
<del> {
<del> return super.onSearchRequested();
<del> }
<del> }
<del>
<del> protected void onStart()
<del> {
<del> if (__ho149)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onStart", args);
<del> }
<del> else
<del> {
<del> super.onStart();
<del> }
<del> }
<del>
<del> protected void onStop()
<del> {
<del> if (__ho150)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onStop", args);
<del> }
<del> else
<del> {
<del> super.onStop();
<del> }
<del> }
<del>
<del> protected void onTitleChanged(java.lang.CharSequence param_0, int param_1)
<del> {
<del> if (__ho151)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "onTitleChanged", args);
<del> }
<del> else
<del> {
<del> super.onTitleChanged(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean onTouchEvent(android.view.MotionEvent param_0)
<del> {
<del> if (__ho152)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onTouchEvent", args);
<del> }
<del> else
<del> {
<del> return super.onTouchEvent(param_0);
<del> }
<del> }
<del>
<del> public boolean onTrackballEvent(android.view.MotionEvent param_0)
<del> {
<del> if (__ho153)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "onTrackballEvent", args);
<del> }
<del> else
<del> {
<del> return super.onTrackballEvent(param_0);
<del> }
<del> }
<del>
<del> public void onTrimMemory(int param_0)
<del> {
<del> if (__ho154)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onTrimMemory", args);
<del> }
<del> else
<del> {
<del> super.onTrimMemory(param_0);
<del> }
<del> }
<del>
<del> public void onUserInteraction()
<del> {
<del> if (__ho155)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onUserInteraction", args);
<del> }
<del> else
<del> {
<del> super.onUserInteraction();
<del> }
<del> }
<del>
<del> protected void onUserLeaveHint()
<del> {
<del> if (__ho156)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "onUserLeaveHint", args);
<del> }
<del> else
<del> {
<del> super.onUserLeaveHint();
<del> }
<del> }
<del>
<del> public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams param_0)
<del> {
<del> if (__ho157)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onWindowAttributesChanged", args);
<del> }
<del> else
<del> {
<del> super.onWindowAttributesChanged(param_0);
<del> }
<del> }
<del>
<del> public void onWindowFocusChanged(boolean param_0)
<del> {
<del> if (__ho158)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "onWindowFocusChanged", args);
<del> }
<del> else
<del> {
<del> super.onWindowFocusChanged(param_0);
<del> }
<del> }
<del>
<del> public android.view.ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback param_0)
<del> {
<del> if (__ho159)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "onWindowStartingActionMode", args);
<del> }
<del> else
<del> {
<del> return super.onWindowStartingActionMode(param_0);
<del> }
<del> }
<del>
<del> public void openContextMenu(android.view.View param_0)
<del> {
<del> if (__ho160)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "openContextMenu", args);
<del> }
<del> else
<del> {
<del> super.openContextMenu(param_0);
<del> }
<del> }
<del>
<del> public java.io.FileInputStream openFileInput(java.lang.String param_0) throws java.io.FileNotFoundException
<del> {
<del> if (__ho161)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (java.io.FileInputStream)com.tns.Platform.callJSMethod(this, "openFileInput", args);
<del> }
<del> else
<del> {
<del> return super.openFileInput(param_0);
<del> }
<del> }
<del>
<del> public java.io.FileOutputStream openFileOutput(java.lang.String param_0, int param_1) throws java.io.FileNotFoundException
<del> {
<del> if (__ho162)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (java.io.FileOutputStream)com.tns.Platform.callJSMethod(this, "openFileOutput", args);
<del> }
<del> else
<del> {
<del> return super.openFileOutput(param_0, param_1);
<del> }
<del> }
<del>
<del> public void openOptionsMenu()
<del> {
<del> if (__ho163)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "openOptionsMenu", args);
<del> }
<del> else
<del> {
<del> super.openOptionsMenu();
<del> }
<del> }
<del>
<del> public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2, android.database.DatabaseErrorHandler param_3)
<del> {
<del> if (__ho164)
<del> {
<del> Object[] args = new Object[4];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", args);
<del> }
<del> else
<del> {
<del> return super.openOrCreateDatabase(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String param_0, int param_1, android.database.sqlite.SQLiteDatabase.CursorFactory param_2)
<del> {
<del> if (__ho164)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> return (android.database.sqlite.SQLiteDatabase)com.tns.Platform.callJSMethod(this, "openOrCreateDatabase", args);
<del> }
<del> else
<del> {
<del> return super.openOrCreateDatabase(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public void overridePendingTransition(int param_0, int param_1)
<del> {
<del> if (__ho165)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "overridePendingTransition", args);
<del> }
<del> else
<del> {
<del> super.overridePendingTransition(param_0, param_1);
<del> }
<del> }
<del>
<del> public android.graphics.drawable.Drawable peekWallpaper()
<del> {
<del> if (__ho166)
<del> {
<del> Object[] args = null;
<del> return (android.graphics.drawable.Drawable)com.tns.Platform.callJSMethod(this, "peekWallpaper", args);
<del> }
<del> else
<del> {
<del> return super.peekWallpaper();
<del> }
<del> }
<del>
<del> public void recreate()
<del> {
<del> if (__ho167)
<del> {
<del> Object[] args = null;
<del> com.tns.Platform.callJSMethod(this, "recreate", args);
<del> }
<del> else
<del> {
<del> super.recreate();
<del> }
<del> }
<del>
<del> public void registerComponentCallbacks(android.content.ComponentCallbacks param_0)
<del> {
<del> if (__ho168)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "registerComponentCallbacks", args);
<del> }
<del> else
<del> {
<del> super.registerComponentCallbacks(param_0);
<del> }
<del> }
<del>
<del> public void registerForContextMenu(android.view.View param_0)
<del> {
<del> if (__ho169)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "registerForContextMenu", args);
<del> }
<del> else
<del> {
<del> super.registerForContextMenu(param_0);
<del> }
<del> }
<del>
<del> public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1, java.lang.String param_2, android.os.Handler param_3)
<del> {
<del> if (__ho170)
<del> {
<del> Object[] args = new Object[4];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", args);
<del> }
<del> else
<del> {
<del> return super.registerReceiver(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> public android.content.Intent registerReceiver(android.content.BroadcastReceiver param_0, android.content.IntentFilter param_1)
<del> {
<del> if (__ho170)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (android.content.Intent)com.tns.Platform.callJSMethod(this, "registerReceiver", args);
<del> }
<del> else
<del> {
<del> return super.registerReceiver(param_0, param_1);
<del> }
<del> }
<del>
<del> public void removeStickyBroadcast(android.content.Intent param_0)
<del> {
<del> if (__ho171)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "removeStickyBroadcast", args);
<del> }
<del> else
<del> {
<del> super.removeStickyBroadcast(param_0);
<del> }
<del> }
<del>
<del> public void removeStickyBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
<del> {
<del> if (__ho172)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "removeStickyBroadcastAsUser", args);
<del> }
<del> else
<del> {
<del> super.removeStickyBroadcastAsUser(param_0, param_1);
<del> }
<del> }
<del>
<del> public void revokeUriPermission(android.net.Uri param_0, int param_1)
<del> {
<del> if (__ho173)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "revokeUriPermission", args);
<del> }
<del> else
<del> {
<del> super.revokeUriPermission(param_0, param_1);
<del> }
<del> }
<del>
<del> public void sendBroadcast(android.content.Intent param_0, java.lang.String param_1)
<del> {
<del> if (__ho174)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "sendBroadcast", args);
<del> }
<del> else
<del> {
<del> super.sendBroadcast(param_0, param_1);
<del> }
<del> }
<del>
<del> public void sendBroadcast(android.content.Intent param_0)
<del> {
<del> if (__ho174)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "sendBroadcast", args);
<del> }
<del> else
<del> {
<del> super.sendBroadcast(param_0);
<del> }
<del> }
<del>
<del> public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1)
<del> {
<del> if (__ho175)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", args);
<add> com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> super.sendBroadcastAsUser(param_0, param_1);
<del> }
<del> }
<del>
<del> public void sendBroadcastAsUser(android.content.Intent param_0, android.os.UserHandle param_1, java.lang.String param_2)
<del> {
<del> if (__ho175)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "sendBroadcastAsUser", args);
<del> }
<del> else
<del> {
<del> super.sendBroadcastAsUser(param_0, param_1, param_2);
<ide> }
<ide> }
<ide>
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<del> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", args);
<add> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", args);
<add> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcast", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<ide> args[7] = param_7;
<del> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcastAsUser", args);
<add> com.tns.Platform.callJSMethod(this, "sendOrderedBroadcastAsUser", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "sendStickyBroadcast", args);
<add> com.tns.Platform.callJSMethod(this, "sendStickyBroadcast", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "sendStickyBroadcastAsUser", args);
<add> com.tns.Platform.callJSMethod(this, "sendStickyBroadcastAsUser", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[3] = param_3;
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<del> com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcast", args);
<add> com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcast", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<del> com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcastAsUser", args);
<add> com.tns.Platform.callJSMethod(this, "sendStickyOrderedBroadcastAsUser", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<add> public void setContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
<add> {
<add> if (__ho182)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
<add> }
<add> else
<add> {
<add> super.setContentView(param_0, param_1);
<add> }
<add> }
<add>
<ide> public void setContentView(int param_0)
<ide> {
<ide> if (__ho182)
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setContentView", args);
<add> com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<del> public void setContentView(android.view.View param_0, android.view.ViewGroup.LayoutParams param_1)
<add> public void setContentView(android.view.View param_0)
<ide> {
<ide> if (__ho182)
<ide> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setContentView", void.class, args);
<add> }
<add> else
<add> {
<add> super.setContentView(param_0);
<add> }
<add> }
<add>
<add> public void setFinishOnTouchOutside(boolean param_0)
<add> {
<add> if (__ho183)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setFinishOnTouchOutside", void.class, args);
<add> }
<add> else
<add> {
<add> super.setFinishOnTouchOutside(param_0);
<add> }
<add> }
<add>
<add> public void setIntent(android.content.Intent param_0)
<add> {
<add> if (__ho184)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setIntent", void.class, args);
<add> }
<add> else
<add> {
<add> super.setIntent(param_0);
<add> }
<add> }
<add>
<add> public void setRequestedOrientation(int param_0)
<add> {
<add> if (__ho185)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setRequestedOrientation", void.class, args);
<add> }
<add> else
<add> {
<add> super.setRequestedOrientation(param_0);
<add> }
<add> }
<add>
<add> public void setTheme(int param_0)
<add> {
<add> if (__ho186)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setTheme", void.class, args);
<add> }
<add> else
<add> {
<add> super.setTheme(param_0);
<add> }
<add> }
<add>
<add> public void setTitle(int param_0)
<add> {
<add> if (__ho187)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setTitle", void.class, args);
<add> }
<add> else
<add> {
<add> super.setTitle(param_0);
<add> }
<add> }
<add>
<add> public void setTitle(java.lang.CharSequence param_0)
<add> {
<add> if (__ho187)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setTitle", void.class, args);
<add> }
<add> else
<add> {
<add> super.setTitle(param_0);
<add> }
<add> }
<add>
<add> public void setTitleColor(int param_0)
<add> {
<add> if (__ho188)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setTitleColor", void.class, args);
<add> }
<add> else
<add> {
<add> super.setTitleColor(param_0);
<add> }
<add> }
<add>
<add> public void setVisible(boolean param_0)
<add> {
<add> if (__ho189)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setVisible", void.class, args);
<add> }
<add> else
<add> {
<add> super.setVisible(param_0);
<add> }
<add> }
<add>
<add> public void setWallpaper(java.io.InputStream param_0) throws java.io.IOException
<add> {
<add> if (__ho190)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setWallpaper", void.class, args);
<add> }
<add> else
<add> {
<add> super.setWallpaper(param_0);
<add> }
<add> }
<add>
<add> public void setWallpaper(android.graphics.Bitmap param_0) throws java.io.IOException
<add> {
<add> if (__ho190)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "setWallpaper", void.class, args);
<add> }
<add> else
<add> {
<add> super.setWallpaper(param_0);
<add> }
<add> }
<add>
<add> public boolean shouldUpRecreateTask(android.content.Intent param_0)
<add> {
<add> if (__ho191)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "shouldUpRecreateTask", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.shouldUpRecreateTask(param_0);
<add> }
<add> }
<add>
<add> public android.view.ActionMode startActionMode(android.view.ActionMode.Callback param_0)
<add> {
<add> if (__ho192)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "startActionMode", android.view.ActionMode.class, args);
<add> }
<add> else
<add> {
<add> return super.startActionMode(param_0);
<add> }
<add> }
<add>
<add> public void startActivities(android.content.Intent[] param_0)
<add> {
<add> if (__ho193)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "startActivities", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivities(param_0);
<add> }
<add> }
<add>
<add> public void startActivities(android.content.Intent[] param_0, android.os.Bundle param_1)
<add> {
<add> if (__ho193)
<add> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "setContentView", args);
<del> }
<del> else
<del> {
<del> super.setContentView(param_0, param_1);
<del> }
<del> }
<del>
<del> public void setContentView(android.view.View param_0)
<del> {
<del> if (__ho182)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setContentView", args);
<del> }
<del> else
<del> {
<del> super.setContentView(param_0);
<del> }
<del> }
<del>
<del> public void setFinishOnTouchOutside(boolean param_0)
<del> {
<del> if (__ho183)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setFinishOnTouchOutside", args);
<del> }
<del> else
<del> {
<del> super.setFinishOnTouchOutside(param_0);
<del> }
<del> }
<del>
<del> public void setIntent(android.content.Intent param_0)
<del> {
<del> if (__ho184)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setIntent", args);
<del> }
<del> else
<del> {
<del> super.setIntent(param_0);
<del> }
<del> }
<del>
<del> public void setRequestedOrientation(int param_0)
<del> {
<del> if (__ho185)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setRequestedOrientation", args);
<del> }
<del> else
<del> {
<del> super.setRequestedOrientation(param_0);
<del> }
<del> }
<del>
<del> public void setTheme(int param_0)
<del> {
<del> if (__ho186)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setTheme", args);
<del> }
<del> else
<del> {
<del> super.setTheme(param_0);
<del> }
<del> }
<del>
<del> public void setTitle(java.lang.CharSequence param_0)
<del> {
<del> if (__ho187)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setTitle", args);
<del> }
<del> else
<del> {
<del> super.setTitle(param_0);
<del> }
<del> }
<del>
<del> public void setTitle(int param_0)
<del> {
<del> if (__ho187)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setTitle", args);
<del> }
<del> else
<del> {
<del> super.setTitle(param_0);
<del> }
<del> }
<del>
<del> public void setTitleColor(int param_0)
<del> {
<del> if (__ho188)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setTitleColor", args);
<del> }
<del> else
<del> {
<del> super.setTitleColor(param_0);
<del> }
<del> }
<del>
<del> public void setVisible(boolean param_0)
<del> {
<del> if (__ho189)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setVisible", args);
<del> }
<del> else
<del> {
<del> super.setVisible(param_0);
<del> }
<del> }
<del>
<del> public void setWallpaper(java.io.InputStream param_0) throws java.io.IOException
<del> {
<del> if (__ho190)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setWallpaper", args);
<del> }
<del> else
<del> {
<del> super.setWallpaper(param_0);
<del> }
<del> }
<del>
<del> public void setWallpaper(android.graphics.Bitmap param_0) throws java.io.IOException
<del> {
<del> if (__ho190)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "setWallpaper", args);
<del> }
<del> else
<del> {
<del> super.setWallpaper(param_0);
<del> }
<del> }
<del>
<del> public boolean shouldUpRecreateTask(android.content.Intent param_0)
<del> {
<del> if (__ho191)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "shouldUpRecreateTask", args);
<del> }
<del> else
<del> {
<del> return super.shouldUpRecreateTask(param_0);
<del> }
<del> }
<del>
<del> public android.view.ActionMode startActionMode(android.view.ActionMode.Callback param_0)
<del> {
<del> if (__ho192)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (android.view.ActionMode)com.tns.Platform.callJSMethod(this, "startActionMode", args);
<del> }
<del> else
<del> {
<del> return super.startActionMode(param_0);
<del> }
<del> }
<del>
<del> public void startActivities(android.content.Intent[] param_0, android.os.Bundle param_1)
<del> {
<del> if (__ho193)
<add> com.tns.Platform.callJSMethod(this, "startActivities", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivities(param_0, param_1);
<add> }
<add> }
<add>
<add> public void startActivity(android.content.Intent param_0, android.os.Bundle param_1)
<add> {
<add> if (__ho194)
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "startActivities", args);
<del> }
<del> else
<del> {
<del> super.startActivities(param_0, param_1);
<del> }
<del> }
<del>
<del> public void startActivities(android.content.Intent[] param_0)
<del> {
<del> if (__ho193)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "startActivities", args);
<del> }
<del> else
<del> {
<del> super.startActivities(param_0);
<del> }
<del> }
<del>
<del> public void startActivity(android.content.Intent param_0, android.os.Bundle param_1)
<add> com.tns.Platform.callJSMethod(this, "startActivity", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivity(param_0, param_1);
<add> }
<add> }
<add>
<add> public void startActivity(android.content.Intent param_0)
<ide> {
<ide> if (__ho194)
<ide> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "startActivity", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivity(param_0);
<add> }
<add> }
<add>
<add> public void startActivityForResult(android.content.Intent param_0, int param_1)
<add> {
<add> if (__ho195)
<add> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "startActivity", args);
<del> }
<del> else
<del> {
<del> super.startActivity(param_0, param_1);
<del> }
<del> }
<del>
<del> public void startActivity(android.content.Intent param_0)
<del> {
<del> if (__ho194)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "startActivity", args);
<del> }
<del> else
<del> {
<del> super.startActivity(param_0);
<del> }
<del> }
<del>
<del> public void startActivityForResult(android.content.Intent param_0, int param_1)
<add> com.tns.Platform.callJSMethod(this, "startActivityForResult", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityForResult(param_0, param_1);
<add> }
<add> }
<add>
<add> public void startActivityForResult(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
<ide> {
<ide> if (__ho195)
<ide> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> com.tns.Platform.callJSMethod(this, "startActivityForResult", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityForResult(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2)
<add> {
<add> if (__ho196)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> com.tns.Platform.callJSMethod(this, "startActivityFromChild", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityFromChild(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
<add> {
<add> if (__ho196)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> com.tns.Platform.callJSMethod(this, "startActivityFromChild", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityFromChild(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<add> public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2)
<add> {
<add> if (__ho197)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> com.tns.Platform.callJSMethod(this, "startActivityFromFragment", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityFromFragment(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
<add> {
<add> if (__ho197)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> com.tns.Platform.callJSMethod(this, "startActivityFromFragment", void.class, args);
<add> }
<add> else
<add> {
<add> super.startActivityFromFragment(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<add> public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1)
<add> {
<add> if (__ho198)
<add> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "startActivityForResult", args);
<del> }
<del> else
<del> {
<del> super.startActivityForResult(param_0, param_1);
<del> }
<del> }
<del>
<del> public void startActivityForResult(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
<del> {
<del> if (__ho195)
<add> return (boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.startActivityIfNeeded(param_0, param_1);
<add> }
<add> }
<add>
<add> public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
<add> {
<add> if (__ho198)
<ide> {
<ide> Object[] args = new Object[3];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "startActivityForResult", args);
<del> }
<del> else
<del> {
<del> super.startActivityForResult(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
<del> {
<del> if (__ho196)
<del> {
<del> Object[] args = new Object[4];
<add> return (boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.startActivityIfNeeded(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public boolean startInstrumentation(android.content.ComponentName param_0, java.lang.String param_1, android.os.Bundle param_2)
<add> {
<add> if (__ho199)
<add> {
<add> Object[] args = new Object[3];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "startInstrumentation", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.startInstrumentation(param_0, param_1, param_2);
<add> }
<add> }
<add>
<add> public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4) throws android.content.IntentSender.SendIntentException
<add> {
<add> if (__ho200)
<add> {
<add> Object[] args = new Object[5];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<ide> args[2] = param_2;
<ide> args[3] = param_3;
<del> com.tns.Platform.callJSMethod(this, "startActivityFromChild", args);
<del> }
<del> else
<del> {
<del> super.startActivityFromChild(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> public void startActivityFromChild(android.app.Activity param_0, android.content.Intent param_1, int param_2)
<del> {
<del> if (__ho196)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "startActivityFromChild", args);
<del> }
<del> else
<del> {
<del> super.startActivityFromChild(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2)
<del> {
<del> if (__ho197)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> com.tns.Platform.callJSMethod(this, "startActivityFromFragment", args);
<del> }
<del> else
<del> {
<del> super.startActivityFromFragment(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public void startActivityFromFragment(android.app.Fragment param_0, android.content.Intent param_1, int param_2, android.os.Bundle param_3)
<del> {
<del> if (__ho197)
<del> {
<del> Object[] args = new Object[4];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> com.tns.Platform.callJSMethod(this, "startActivityFromFragment", args);
<del> }
<del> else
<del> {
<del> super.startActivityFromFragment(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1)
<del> {
<del> if (__ho198)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", args);
<del> }
<del> else
<del> {
<del> return super.startActivityIfNeeded(param_0, param_1);
<del> }
<del> }
<del>
<del> public boolean startActivityIfNeeded(android.content.Intent param_0, int param_1, android.os.Bundle param_2)
<del> {
<del> if (__ho198)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "startActivityIfNeeded", args);
<del> }
<del> else
<del> {
<del> return super.startActivityIfNeeded(param_0, param_1, param_2);
<del> }
<del> }
<del>
<del> public boolean startInstrumentation(android.content.ComponentName param_0, java.lang.String param_1, android.os.Bundle param_2)
<del> {
<del> if (__ho199)
<del> {
<del> Object[] args = new Object[3];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "startInstrumentation", args);
<del> }
<del> else
<del> {
<del> return super.startInstrumentation(param_0, param_1, param_2);
<add> args[4] = param_4;
<add> com.tns.Platform.callJSMethod(this, "startIntentSender", void.class, args);
<add> }
<add> else
<add> {
<add> super.startIntentSender(param_0, param_1, param_2, param_3, param_4);
<ide> }
<ide> }
<ide>
<ide> args[3] = param_3;
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<del> com.tns.Platform.callJSMethod(this, "startIntentSender", args);
<add> com.tns.Platform.callJSMethod(this, "startIntentSender", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> super.startIntentSender(param_0, param_1, param_2, param_3, param_4, param_5);
<del> }
<del> }
<del>
<del> public void startIntentSender(android.content.IntentSender param_0, android.content.Intent param_1, int param_2, int param_3, int param_4) throws android.content.IntentSender.SendIntentException
<del> {
<del> if (__ho200)
<del> {
<del> Object[] args = new Object[5];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> args[4] = param_4;
<del> com.tns.Platform.callJSMethod(this, "startIntentSender", args);
<del> }
<del> else
<del> {
<del> super.startIntentSender(param_0, param_1, param_2, param_3, param_4);
<ide> }
<ide> }
<ide>
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<del> com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", args);
<add> com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[3] = param_3;
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<del> com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", args);
<add> com.tns.Platform.callJSMethod(this, "startIntentSenderForResult", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<ide> args[7] = param_7;
<del> com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", args);
<add> com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> args[4] = param_4;
<ide> args[5] = param_5;
<ide> args[6] = param_6;
<del> com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", args);
<add> com.tns.Platform.callJSMethod(this, "startIntentSenderFromChild", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "startManagingCursor", args);
<add> com.tns.Platform.callJSMethod(this, "startManagingCursor", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<add> public boolean startNextMatchingActivity(android.content.Intent param_0, android.os.Bundle param_1)
<add> {
<add> if (__ho204)
<add> {
<add> Object[] args = new Object[2];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.startNextMatchingActivity(param_0, param_1);
<add> }
<add> }
<add>
<ide> public boolean startNextMatchingActivity(android.content.Intent param_0)
<ide> {
<ide> if (__ho204)
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", args);
<add> return (boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", boolean.class, args);
<ide> }
<ide> else
<ide> {
<ide> }
<ide> }
<ide>
<del> public boolean startNextMatchingActivity(android.content.Intent param_0, android.os.Bundle param_1)
<del> {
<del> if (__ho204)
<add> public void startSearch(java.lang.String param_0, boolean param_1, android.os.Bundle param_2, boolean param_3)
<add> {
<add> if (__ho205)
<add> {
<add> Object[] args = new Object[4];
<add> args[0] = param_0;
<add> args[1] = param_1;
<add> args[2] = param_2;
<add> args[3] = param_3;
<add> com.tns.Platform.callJSMethod(this, "startSearch", void.class, args);
<add> }
<add> else
<add> {
<add> super.startSearch(param_0, param_1, param_2, param_3);
<add> }
<add> }
<add>
<add> public android.content.ComponentName startService(android.content.Intent param_0)
<add> {
<add> if (__ho206)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "startService", android.content.ComponentName.class, args);
<add> }
<add> else
<add> {
<add> return super.startService(param_0);
<add> }
<add> }
<add>
<add> public void stopManagingCursor(android.database.Cursor param_0)
<add> {
<add> if (__ho207)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "stopManagingCursor", void.class, args);
<add> }
<add> else
<add> {
<add> super.stopManagingCursor(param_0);
<add> }
<add> }
<add>
<add> public boolean stopService(android.content.Intent param_0)
<add> {
<add> if (__ho208)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> return (boolean)com.tns.Platform.callJSMethod(this, "stopService", boolean.class, args);
<add> }
<add> else
<add> {
<add> return super.stopService(param_0);
<add> }
<add> }
<add>
<add> public void takeKeyEvents(boolean param_0)
<add> {
<add> if (__ho209)
<add> {
<add> Object[] args = new Object[1];
<add> args[0] = param_0;
<add> com.tns.Platform.callJSMethod(this, "takeKeyEvents", void.class, args);
<add> }
<add> else
<add> {
<add> super.takeKeyEvents(param_0);
<add> }
<add> }
<add>
<add> public java.lang.String toString()
<add> {
<add> if (__ho210)
<add> {
<add> Object[] args = null;
<add> return (java.lang.String)com.tns.Platform.callJSMethod(this, "toString", java.lang.String.class, args);
<add> }
<add> else
<add> {
<add> return super.toString();
<add> }
<add> }
<add>
<add> public void triggerSearch(java.lang.String param_0, android.os.Bundle param_1)
<add> {
<add> if (__ho211)
<ide> {
<ide> Object[] args = new Object[2];
<ide> args[0] = param_0;
<ide> args[1] = param_1;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "startNextMatchingActivity", args);
<del> }
<del> else
<del> {
<del> return super.startNextMatchingActivity(param_0, param_1);
<del> }
<del> }
<del>
<del> public void startSearch(java.lang.String param_0, boolean param_1, android.os.Bundle param_2, boolean param_3)
<del> {
<del> if (__ho205)
<del> {
<del> Object[] args = new Object[4];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> args[2] = param_2;
<del> args[3] = param_3;
<del> com.tns.Platform.callJSMethod(this, "startSearch", args);
<del> }
<del> else
<del> {
<del> super.startSearch(param_0, param_1, param_2, param_3);
<del> }
<del> }
<del>
<del> public android.content.ComponentName startService(android.content.Intent param_0)
<del> {
<del> if (__ho206)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (android.content.ComponentName)com.tns.Platform.callJSMethod(this, "startService", args);
<del> }
<del> else
<del> {
<del> return super.startService(param_0);
<del> }
<del> }
<del>
<del> public void stopManagingCursor(android.database.Cursor param_0)
<del> {
<del> if (__ho207)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "stopManagingCursor", args);
<del> }
<del> else
<del> {
<del> super.stopManagingCursor(param_0);
<del> }
<del> }
<del>
<del> public boolean stopService(android.content.Intent param_0)
<del> {
<del> if (__ho208)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> return (Boolean)com.tns.Platform.callJSMethod(this, "stopService", args);
<del> }
<del> else
<del> {
<del> return super.stopService(param_0);
<del> }
<del> }
<del>
<del> public void takeKeyEvents(boolean param_0)
<del> {
<del> if (__ho209)
<del> {
<del> Object[] args = new Object[1];
<del> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "takeKeyEvents", args);
<del> }
<del> else
<del> {
<del> super.takeKeyEvents(param_0);
<del> }
<del> }
<del>
<del> public java.lang.String toString()
<del> {
<del> if (__ho210)
<del> {
<del> Object[] args = null;
<del> return (java.lang.String)com.tns.Platform.callJSMethod(this, "toString", args);
<del> }
<del> else
<del> {
<del> return super.toString();
<del> }
<del> }
<del>
<del> public void triggerSearch(java.lang.String param_0, android.os.Bundle param_1)
<del> {
<del> if (__ho211)
<del> {
<del> Object[] args = new Object[2];
<del> args[0] = param_0;
<del> args[1] = param_1;
<del> com.tns.Platform.callJSMethod(this, "triggerSearch", args);
<add> com.tns.Platform.callJSMethod(this, "triggerSearch", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "unbindService", args);
<add> com.tns.Platform.callJSMethod(this, "unbindService", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "unregisterComponentCallbacks", args);
<add> com.tns.Platform.callJSMethod(this, "unregisterComponentCallbacks", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "unregisterForContextMenu", args);
<add> com.tns.Platform.callJSMethod(this, "unregisterForContextMenu", void.class, args);
<ide> }
<ide> else
<ide> {
<ide> {
<ide> Object[] args = new Object[1];
<ide> args[0] = param_0;
<del> com.tns.Platform.callJSMethod(this, "unregisterReceiver", args);
<add> com.tns.Platform.callJSMethod(this, "unregisterReceiver", void.class, args);
<ide> }
<ide> else
<ide> { |
|
Java | apache-2.0 | error: pathspec 'MyTracks/src/com/google/android/apps/mytracks/services/sensors/PolarSensorManager.java' did not match any file(s) known to git
| 90afc1e2212bfaabe6a3580f6d31acd7b4a5eb31 | 1 | Plonk42/mytracks | /*
* Copyright 2011 Google 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.google.android.apps.mytracks.services.sensors;
import android.content.Context;
/**
* PolarSensorManager - Straight copy from ZephyrSensorManager, renamed, of course.
*/
public class PolarSensorManager extends BluetoothSensorManager {
public PolarSensorManager(Context context) {
super(context, new PolarMessageParser());
}
}
| MyTracks/src/com/google/android/apps/mytracks/services/sensors/PolarSensorManager.java | Polar parser
| MyTracks/src/com/google/android/apps/mytracks/services/sensors/PolarSensorManager.java | Polar parser | <ide><path>yTracks/src/com/google/android/apps/mytracks/services/sensors/PolarSensorManager.java
<add>/*
<add> * Copyright 2011 Google Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not
<add> * use this file except in compliance with the License. You may obtain a copy of
<add> * 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, WITHOUT
<add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
<add> * License for the specific language governing permissions and limitations under
<add> * the License.
<add> */
<add>package com.google.android.apps.mytracks.services.sensors;
<add>
<add>import android.content.Context;
<add>
<add>/**
<add> * PolarSensorManager - Straight copy from ZephyrSensorManager, renamed, of course.
<add> */
<add>
<add>public class PolarSensorManager extends BluetoothSensorManager {
<add> public PolarSensorManager(Context context) {
<add> super(context, new PolarMessageParser());
<add> }
<add>} |
|
Java | mit | e9409e56b43b7fd2c6aa71c02954cf9c93771856 | 0 | SysLord/slide-gen | package de.syslord.boxmodel;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import de.syslord.boxmodel.renderer.RenderType;
import de.syslord.boxmodel.renderer.RenderableBoxImpl;
public class LayoutableBox {
private Map<Object, Integer> layoutProperties = new HashMap<>();
private List<LayoutableBox> children = new ArrayList<>();
protected String name;
protected ByteArrayInputStream backgroundImage;
protected Color foregroundColor = Color.BLACK;
// fix values
protected int x = 0;
protected int initialY = 0;
protected int width = 0;
protected int initialHeight = 0;
// calculated values
protected int heightNeeded = 0;
protected int height = 0;
protected int y = 0;
protected int absoluteY = 0;
protected int absoluteX;
protected boolean visible = true;
protected String styleIdentifier = "";
//
public LayoutableBox(String name, int x, int y, int width, int height) {
this.name = name;
this.x = x;
this.y = y;
this.initialY = y;
this.width = width;
this.height = height;
this.initialHeight = height;
}
public static LayoutableBox createFixedHeightBox(String name, int x, int y, int width, int height) {
LayoutableBox box = new LayoutableBox(name, x, y, width, height);
box.setProp(HeightProperty.MIN, height);
box.setProp(HeightProperty.MAX, height);
return box;
}
public RenderableBoxImpl toRenderable() {
RenderableBoxImpl renderableBoxImpl = new RenderableBoxImpl(
absoluteX, absoluteY, width, height,
visible);
renderableBoxImpl.setColor(foregroundColor);
renderableBoxImpl.setBackgroundImage(backgroundImage);
renderableBoxImpl.setRenderType(RenderType.BOX);
return renderableBoxImpl;
}
public void applyStyle(Style style) {
style.getColor(styleIdentifier).ifPresent(c -> foregroundColor = c);
children.stream().forEach(child -> child.applyStyle(style));
}
public int getHeightChanged() {
return height - initialHeight;
}
public void setHeightNeeded(int heightNeeded) {
this.heightNeeded = heightNeeded;
}
public void setProp(Object property, Integer value) {
if (value == null) {
layoutProperties.remove(property);
} else {
layoutProperties.put(property, value);
}
}
public void setProp(Object property) {
if (property != null) {
layoutProperties.put(property, null);
}
}
public void setPropIf(Object property, boolean doSet) {
if (doSet) {
layoutProperties.put(property, null);
}
}
public void addChild(LayoutableBox child) {
children.add(child);
}
public void addChildren(LayoutableBox... newChildren) {
for (LayoutableBox child : newChildren) {
children.add(child);
}
}
public List<LayoutableBox> getChildren() {
return children;
}
public boolean hasChildren() {
return children.size() > 0;
}
public boolean hasProp(Object key) {
return layoutProperties.containsKey(key);
}
public boolean hasProp(Object key, Object value) {
return layoutProperties.containsKey(key) && layoutProperties.get(key) == value;
}
public Integer getProp(Object key) {
return layoutProperties.get(key);
}
public void setHeight(int set, boolean allowShrinking) {
int newsize = set;
if (hasProp(HeightProperty.MIN)) {
int min = getProp(HeightProperty.MIN);
if (newsize < min) {
newsize = min;
}
}
if (hasProp(HeightProperty.MAX)) {
int max = getProp(HeightProperty.MAX);
if (newsize > max) {
newsize = Math.max(max, 0);
}
}
if (allowShrinking || newsize > height) {
height = newsize;
}
}
public void updateSizeIncludingYLimits(int parentHeight) {
int maxPossibleHeight = parentHeight - y;
// for example lines may have height 0
if (maxPossibleHeight < 0) {
visible = false;
}
if (height > maxPossibleHeight) {
height = maxPossibleHeight;
}
}
public void setY(int set) {
int newY = set;
if (newY < y && hasProp(PositionProperty.FLOAT_UP)) {
// float only up to 0
this.y = Math.max(0, newY);
} else if (newY > y && hasProp(PositionProperty.FLOAT_DOWN)) {
// floating off parent area downwards is allowed
this.y = newY;
}
}
public Stream<LayoutableBox> streamFlat() {
if (getChildren().isEmpty()) {
return Stream.of(this);
} else {
Stream<LayoutableBox> reduce = getChildren().stream()
.map(child -> child.streamFlat())
.reduce(Stream.of(this), (s1, s2) -> Stream.concat(s1, s2));
return reduce;
}
}
public int getWidth() {
return width;
}
public String getName() {
return name;
}
public int getX() {
return x;
}
public int getHeightNeeded() {
return heightNeeded;
}
public int getInitialHeight() {
return initialHeight;
}
public int getHeight() {
return height;
}
public int getY() {
return y;
}
public int getAbsoluteY() {
return absoluteY;
}
public int getAbsoluteX() {
return absoluteX;
}
public void setAbsoluteY(int absoluteY) {
this.absoluteY = absoluteY;
}
public void setAbsoluteX(int absoluteX) {
this.absoluteX = absoluteX;
}
public boolean isVisible() {
return visible;
}
public void setBackgroundImage(ByteArrayInputStream backgroundImage) {
this.backgroundImage = backgroundImage;
}
public void setForegroundColor(Color foregroundColor) {
this.foregroundColor = foregroundColor;
}
public ByteArrayInputStream getBackgroundImage() {
return backgroundImage;
}
public Color getForegroundColor() {
return foregroundColor;
}
public void setStyleName(String styleIdentifier) {
this.styleIdentifier = styleIdentifier;
}
public void setFloat() {
setProp(PositionProperty.FLOAT_UP);
setProp(PositionProperty.FLOAT_DOWN);
}
}
| slideLayoutRenderer/src/main/java/de/syslord/boxmodel/LayoutableBox.java | package de.syslord.boxmodel;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import de.syslord.boxmodel.renderer.RenderType;
import de.syslord.boxmodel.renderer.RenderableBoxImpl;
public class LayoutableBox {
private Map<Object, Integer> layoutProperties = new HashMap<>();
private List<LayoutableBox> children = new ArrayList<>();
protected String name;
protected ByteArrayInputStream backgroundImage;
protected Color foregroundColor = Color.BLACK;
// fix values
protected int x = 0;
protected int initialY = 0;
protected int width = 0;
protected int initialHeight = 0;
// calculated values
protected int heightNeeded = 0;
protected int height = 0;
protected int y = 0;
protected int absoluteY = 0;
protected int absoluteX;
protected boolean visible = true;
protected String styleIdentifier = "";
//
public LayoutableBox(String name, int x, int y, int width, int height) {
this.name = name;
this.x = x;
this.y = y;
this.initialY = y;
this.width = width;
this.height = height;
this.initialHeight = height;
}
public static LayoutableBox createFixedHeightBox(String name, int x, int y, int width, int height) {
LayoutableBox box = new LayoutableBox(name, x, y, width, height);
box.setProp(HeightProperty.MIN, height);
box.setProp(HeightProperty.MAX, height);
return box;
}
public RenderableBoxImpl toRenderable() {
RenderableBoxImpl renderableBoxImpl = new RenderableBoxImpl(
absoluteX, absoluteY, width, height,
visible);
renderableBoxImpl.setColor(foregroundColor);
renderableBoxImpl.setBackgroundImage(backgroundImage);
renderableBoxImpl.setRenderType(RenderType.BOX);
return renderableBoxImpl;
}
public void applyStyle(Style style) {
style.getColor(styleIdentifier).ifPresent(c -> foregroundColor = c);
children.stream().forEach(child -> child.applyStyle(style));
}
public int getHeightChanged() {
return height - initialHeight;
}
public void setHeightNeeded(int heightNeeded) {
this.heightNeeded = heightNeeded;
}
public void setProp(Object property, Integer value) {
if (value == null) {
layoutProperties.remove(property);
} else {
layoutProperties.put(property, value);
}
}
public void setProp(Object property) {
if (property != null) {
layoutProperties.put(property, null);
}
}
public void setPropIf(Object property, boolean doSet) {
if (doSet) {
layoutProperties.put(property, null);
}
}
public void addChild(LayoutableBox child) {
children.add(child);
}
public void addChildren(LayoutableBox... newChildren) {
for (LayoutableBox child : newChildren) {
children.add(child);
}
}
public List<LayoutableBox> getChildren() {
return children;
}
public boolean hasChildren() {
return children.size() > 0;
}
public boolean hasProp(Object key) {
return layoutProperties.containsKey(key);
}
public boolean hasProp(Object key, Object value) {
return layoutProperties.containsKey(key) && layoutProperties.get(key) == value;
}
public Integer getProp(Object key) {
return layoutProperties.get(key);
}
public void setHeight(int set, boolean allowShrinking) {
int newsize = set;
if (hasProp(HeightProperty.MIN)) {
int min = getProp(HeightProperty.MIN);
if (newsize < min) {
newsize = min;
}
}
if (hasProp(HeightProperty.MAX)) {
int max = getProp(HeightProperty.MAX);
if (newsize > max) {
newsize = Math.max(max, 0);
}
}
if (allowShrinking || newsize > height) {
height = newsize;
}
}
public void updateSizeIncludingYLimits(int parentHeight) {
int maxPossibleHeight = parentHeight - y;
// for example lines may have height 0
if (maxPossibleHeight < 0) {
visible = false;
}
if (height > maxPossibleHeight) {
height = maxPossibleHeight;
}
}
public void setY(int set) {
int newY = set;
if (newY < y && hasProp(PositionProperty.FLOAT_UP)) {
// float only up to 0
this.y = Math.max(0, newY);
} else if (newY > y && hasProp(PositionProperty.FLOAT_DOWN)) {
// floating off parent area downwards is allowed
this.y = newY;
}
}
public Stream<LayoutableBox> streamFlat() {
if (getChildren().isEmpty()) {
return Stream.of(this);
} else {
Stream<LayoutableBox> reduce = getChildren().stream()
.map(child -> child.streamFlat())
.reduce(Stream.of(this), (s1, s2) -> Stream.concat(s1, s2));
return reduce;
}
}
public int getWidth() {
return width;
}
public String getName() {
return name;
}
public int getX() {
return x;
}
public int getHeightNeeded() {
return heightNeeded;
}
public int getInitialHeight() {
return initialHeight;
}
public int getHeight() {
return height;
}
public int getY() {
return y;
}
public int getAbsoluteY() {
return absoluteY;
}
public int getAbsoluteX() {
return absoluteX;
}
public void setAbsoluteY(int absoluteY) {
this.absoluteY = absoluteY;
}
public void setAbsoluteX(int absoluteX) {
this.absoluteX = absoluteX;
}
public boolean isVisible() {
return visible;
}
public void setBackgroundImage(ByteArrayInputStream backgroundImage) {
this.backgroundImage = backgroundImage;
}
public void setForegroundColor(Color foregroundColor) {
this.foregroundColor = foregroundColor;
}
public ByteArrayInputStream getBackgroundImage() {
return backgroundImage;
}
public Color getForegroundColor() {
return foregroundColor;
}
public void setStyleName(String styleIdentifier) {
this.styleIdentifier = styleIdentifier;
}
}
| convenience method setFloat
| slideLayoutRenderer/src/main/java/de/syslord/boxmodel/LayoutableBox.java | convenience method setFloat | <ide><path>lideLayoutRenderer/src/main/java/de/syslord/boxmodel/LayoutableBox.java
<ide> this.styleIdentifier = styleIdentifier;
<ide> }
<ide>
<add> public void setFloat() {
<add> setProp(PositionProperty.FLOAT_UP);
<add> setProp(PositionProperty.FLOAT_DOWN);
<add> }
<add>
<ide> } |
|
Java | mit | a6bfa09eee65091c29002b924996374c9f0a8d2d | 0 | c-sung/dust-density-,c-sung/dust-density-,c-sung/dust-density- | package tw.kewang.testserver.api;
import com.google.gson.Gson;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@Path("data")
public class DataApi {
private static volatile List<Member> members = new ArrayList<>();
private final Gson gson = new Gson();
private final Answer noResult = new Answer("not found");
private final Answer yesResult = new Answer("OK");
@POST
public Response post(String body) {
Member mem = gson.fromJson(body, Member.class);
mem.setAns("OK");
members.add(mem);
System.out.println(gson.toJson(mem));
return Response.ok().entity(gson.toJson(yesResult)).build();
}
@Path("{keyword}")
@GET
public Response get(@PathParam("keyword") String keyword) {
Member detRes = detect(keyword);
if (detRes != null) {
String jsonStr = gson.toJson(detRes);
return Response.ok().entity(jsonStr).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keyword}")
@DELETE
public Response del(@PathParam("keyword") String keyword) {
Member detRes = detect(keyword);
if (detRes != null) {
members.remove(detect(keyword));
return Response.ok().entity(gson.toJson(yesResult)).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keyword}/{dataToPut}")
@PUT
public Response put(@PathParam("keyword") String keyword,@PathParam("dataToPut") String dataToPut, String body) {
Member detRes=detect(keyword);
switch (dataToPut){
case "name":
detRes.setName(body);
break;
case "sex":
detRes.setSex(body);
break;
case "age":
detRes.setAge(Integer.parseInt(body));
break;
case "email":
detRes.setEmail(body);
break;
case "phoneNumber":
detRes.setPhoneNumber(body);
break;
default:
return Response.ok().entity(gson.toJson(noResult)).build();
}
return Response.ok().entity(gson.toJson(detRes)).build();
}
private static Member detect(String key) {
for (int numberOfIndex = 0; numberOfIndex < members.size(); numberOfIndex++) {
Member memGet = members.get(numberOfIndex);
if (memGet.getPhoneNumber().equals(key) || memGet.getName().equals(key) || memGet.getEmail().equals(key)) {
return memGet;
}
}
return null;
}
public class Member {
private String name;
private String sex;
private String phoneNumber;
private String email;
private int age;
private String ans;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAns() {
return ans;
}
public void setAns(String ans) {
this.ans = ans;
}
public Member(String name, String sex, int age, String phoneNumber, String email, String ans) {
this.name = name;
this.sex = sex;
this.age = age;
this.phoneNumber = phoneNumber;
this.email = email;
this.ans = ans;
}
}
public class Answer {
private String ans;
public String getAns() {
return ans;
}
public void setAns(String ans) {
this.ans = ans;
}
public Answer(String ans) {
this.ans = ans;
}
}
}
| src/main/java/tw/kewang/testserver/api/DataApi.java | package tw.kewang.testserver.api;
import com.google.gson.Gson;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@Path("data")
public class DataApi {
private static volatile List<Member> members = new ArrayList<>();
private final Gson gson = new Gson();
private final Answer noResult = new Answer("not found");
@POST
public Response post(String body) {
Member mem = gson.fromJson(body, Member.class);
mem.setAns("OK");
members.add(mem);
System.out.println(gson.toJson(mem));
return Response.ok().entity(gson.toJson(mem.getAns())).build();
}
@Path("{keyword}")
@GET
public Response get(@PathParam("keyword") String keyword) {
Member detRes = detect(keyword);
if (detRes != null) {
String jsonStr = gson.toJson(detRes);
return Response.ok().entity(jsonStr).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keyword}")
@DELETE
public Response del(@PathParam("keyword") String keyword) {
Member detRes = detect(keyword);
if (detRes != null) {
members.remove(detect(keyword));
return Response.ok().entity(gson.toJson("ok")).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keyword}/{dataToPut}")
@PUT
public Response put(@PathParam("keyword") String keyword,@PathParam("dataToPut") String dataToPut, String body) {
Member detRes=detect(keyword);
switch (dataToPut){
case "name":
detRes.setName(body);
break;
case "sex":
detRes.setSex(body);
break;
case "age":
detRes.setAge(Integer.parseInt(body));
break;
case "email":
detRes.setEmail(body);
break;
case "phoneNumber":
detRes.setPhoneNumber(body);
break;
default:
return Response.ok().entity(gson.toJson(noResult)).build();
}
return Response.ok().entity(gson.toJson(detRes)).build();
}
private static Member detect(String key) {
for (int numberOfIndex = 0; numberOfIndex < members.size(); numberOfIndex++) {
Member memGet = members.get(numberOfIndex);
if (memGet.getPhoneNumber().equals(key) || memGet.getName().equals(key) || memGet.getEmail().equals(key)) {
return memGet;
}
}
return null;
}
public class Member {
private String name;
private String sex;
private String phoneNumber;
private String email;
private int age;
private String ans;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAns() {
return ans;
}
public void setAns(String ans) {
this.ans = ans;
}
public Member(String name, String sex, int age, String phoneNumber, String email, String ans) {
this.name = name;
this.sex = sex;
this.age = age;
this.phoneNumber = phoneNumber;
this.email = email;
this.ans = ans;
}
}
public class Answer {
private String ans;
public String getAns() {
return ans;
}
public void setAns(String ans) {
this.ans = ans;
}
public Answer(String ans) {
this.ans = ans;
}
}
}
| change OK to JSON
| src/main/java/tw/kewang/testserver/api/DataApi.java | change OK to JSON | <ide><path>rc/main/java/tw/kewang/testserver/api/DataApi.java
<ide> private static volatile List<Member> members = new ArrayList<>();
<ide> private final Gson gson = new Gson();
<ide> private final Answer noResult = new Answer("not found");
<del>
<add> private final Answer yesResult = new Answer("OK");
<ide> @POST
<ide> public Response post(String body) {
<ide> Member mem = gson.fromJson(body, Member.class);
<ide> mem.setAns("OK");
<ide> members.add(mem);
<ide> System.out.println(gson.toJson(mem));
<del> return Response.ok().entity(gson.toJson(mem.getAns())).build();
<add> return Response.ok().entity(gson.toJson(yesResult)).build();
<ide> }
<ide>
<ide>
<ide> Member detRes = detect(keyword);
<ide> if (detRes != null) {
<ide> members.remove(detect(keyword));
<del> return Response.ok().entity(gson.toJson("ok")).build();
<add> return Response.ok().entity(gson.toJson(yesResult)).build();
<ide> } else {
<ide> return Response.ok().entity(gson.toJson(noResult)).build();
<ide> } |
|
Java | apache-2.0 | 50867a77a68874db2f4119cd680d8ef2c4d2eb5c | 0 | JetBrains/jetpad-mapper,timzam/jetpad-mapper | /*
* Copyright 2012-2016 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 jetbrains.jetpad.base;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;
public class AsyncsTest {
@Test
public void constantAsync() {
Async<Integer> c = Asyncs.constant(239);
assertSuccess(c, 239);
}
@Test
public void failureAsync() {
assertFailure(Asyncs.<Integer>failure(new Throwable()));
}
@Test
public void map() {
Async<Integer> c = Asyncs.constant(239);
Async<Integer> mapped = Asyncs.map(c, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}
});
assertSuccess(mapped, 240);
}
@Test
public void mapFailure() {
Async<Integer> failure = Asyncs.failure(new Throwable());
assertFailure(Asyncs.map(failure, new Function<Integer, Object>() {
@Override
public Object apply(Integer input) {
return input + 1;
}
}));
}
@Test(expected = IllegalArgumentException.class)
public void ignoreHandlerException() {
SimpleAsync<Integer> async = new SimpleAsync<>();
Async<Integer> res = Asyncs.map(async, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}
});
res.onSuccess(new Handler<Integer>() {
@Override
public void handle(Integer item) {
throw new IllegalArgumentException();
}
});
res.onFailure(new Handler<Throwable>() {
@Override
public void handle(Throwable item) {
fail();
}
});
async.success(1);
}
@Test
public void mapException() {
Async<Integer> a = Asyncs.constant(1);
assertFailure(Asyncs.map(a, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
throw new RuntimeException("test");
}
}));
}
@Test
public void select() {
Async<Integer> c = Asyncs.constant(239);
Async<Integer> selected = Asyncs.select(c, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.constant(input + 1);
}
});
assertSuccess(selected, 240);
}
@Test
public void selectException() {
Async<Integer> a = Asyncs.constant(1);
assertFailure(Asyncs.select(a, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
throw new RuntimeException("test");
}
}));
}
@Test
public void selectFirstFailure() {
Async<Integer> failure = Asyncs.failure(new Throwable());
assertFailure(Asyncs.select(failure, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.constant(input + 1);
}
}));
}
@Test
public void selectReturnedFailure() {
Async<Integer> async = Asyncs.constant(1);
assertFailure(Asyncs.select(async, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.failure(new Throwable());
}
}));
}
@Test
public void selectReturnsNull() {
Async<Integer> async = Asyncs.constant(1);
assertSuccessNull(Asyncs.select(async, new Function<Integer, Async<Object>>() {
@Override
public Async<Object> apply(Integer input) {
return null;
}
}));
}
@Test
public void parallelSuccess() {
assertSuccessNull(Asyncs.parallel(Asyncs.constant(1), Asyncs.constant(2)));
}
@Test
public void parallelFailure() {
assertFailure(Asyncs.parallel(Asyncs.constant(1), Asyncs.failure(new Throwable())));
}
@Test
public void parallelAlwaysSucceed() {
assertSuccessNull(Asyncs.parallel(Arrays.asList(Asyncs.constant(1), Asyncs.failure(new Throwable())), true));
}
@Test
public void emptyParallel() {
assertSuccessNull(Asyncs.parallel());
}
@Test
public void untilSuccess() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
@Override
public Async<Integer> get() {
return Asyncs.<Integer>constant(1);
}
}), 1);
}
@Test
public void untilSuccessException() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
private int myCntr = 0;
@Override
public Async<Integer> get() {
myCntr++;
if (myCntr < 2) {
throw new RuntimeException();
} else {
return Asyncs.constant(myCntr);
}
}
}), 2);
}
@Test
public void untilSuccessWithFailures() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
private int myCounter;
@Override
public Async<Integer> get() {
if (myCounter++ < 10) {
return Asyncs.failure(new RuntimeException());
}
return Asyncs.constant(1);
}
}), 1);
}
@Test
public void succeededTrue() {
assertTrue(Asyncs.isSucceeded(Asyncs.constant(239)));
}
@Test
public void succeededFalse() {
SimpleAsync<Integer> async = new SimpleAsync<>();
assertFalse(Asyncs.isSucceeded(async));
}
@Test
public void failedTrue() {
assertTrue(Asyncs.isFailed(Asyncs.failure(new RuntimeException())));
}
@Test
public void failedFalse() {
assertFalse(Asyncs.isFailed(Asyncs.constant(null)));
}
private void assertFailure(Async<?> async) {
final Value<Boolean> called = new Value<>(false);
async.onFailure(new Handler<Throwable>() {
@Override
public void handle(Throwable item) {
called.set(true);
}
});
assertTrue(called.get());
}
private <ValueT> void assertSuccess(Async<ValueT> async, ValueT value) {
if (value == null) {
throw new IllegalStateException();
}
final Value<ValueT> result = new Value<>();
async.onSuccess(new Handler<ValueT>() {
@Override
public void handle(ValueT item) {
result.set(item);
}
});
assertEquals(result.get(), value);
}
private <ValueT> void assertSuccessNull(Async<ValueT> async) {
final Value<Object> result = new Value<>(new Object());
async.onSuccess(new Handler<ValueT>() {
@Override
public void handle(ValueT item) {
result.set(item);
}
});
assertNull(result.get());
}
} | util/base/src/test/java/jetbrains/jetpad/base/AsyncsTest.java | /*
* Copyright 2012-2016 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 jetbrains.jetpad.base;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;
public class AsyncsTest {
@Test
public void constantAsync() {
Async<Integer> c = Asyncs.constant(239);
assertSuccess(c, 239);
}
@Test
public void failureAsync() {
assertFailure(Asyncs.<Integer>failure(new Throwable()));
}
@Test
public void map() {
Async<Integer> c = Asyncs.constant(239);
Async<Integer> mapped = Asyncs.map(c, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}
});
assertSuccess(mapped, 240);
}
@Test
public void mapFailure() {
Async<Integer> failure = Asyncs.failure(new Throwable());
assertFailure(Asyncs.map(failure, new Function<Integer, Object>() {
@Override
public Object apply(Integer input) {
return input + 1;
}
}));
}
@Test(expected = IllegalArgumentException.class)
public void ignoreHandlerException() {
SimpleAsync<Integer> async = new SimpleAsync<>();
Async<Integer> res = Asyncs.map(async, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}
});
res.onSuccess(new Handler<Integer>() {
@Override
public void handle(Integer item) {
throw new IllegalArgumentException();
}
});
res.onFailure(new Handler<Throwable>() {
@Override
public void handle(Throwable item) {
fail();
}
});
async.success(1);
}
@Test
public void mapException() {
Async<Integer> a = Asyncs.constant(1);
assertFailure(Asyncs.map(a, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
throw new RuntimeException("test");
}
}));
}
@Test
public void select() {
Async<Integer> c = Asyncs.constant(239);
Async<Integer> selected = Asyncs.select(c, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.constant(input + 1);
}
});
assertSuccess(selected, 240);
}
@Test
public void selectException() {
Async<Integer> a = Asyncs.constant(1);
assertFailure(Asyncs.select(a, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
throw new RuntimeException("test");
}
}));
}
@Test
public void selectFirstFailure() {
Async<Integer> failure = Asyncs.failure(new Throwable());
assertFailure(Asyncs.select(failure, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.constant(input + 1);
}
}));
}
@Test
public void selectReturnedFailure() {
Async<Integer> async = Asyncs.constant(1);
assertFailure(Asyncs.select(async, new Function<Integer, Async<Integer>>() {
@Override
public Async<Integer> apply(Integer input) {
return Asyncs.failure(new Throwable());
}
}));
}
@Test
public void selectReturnsNull() {
Async<Integer> async = Asyncs.constant(1);
assertSuccessNull(Asyncs.select(async, new Function<Integer, Async<Object>>() {
@Override
public Async<Object> apply(Integer input) {
return null;
}
}));
}
@Test
public void parallelSuccess() {
assertSuccessNull(Asyncs.parallel(Asyncs.constant(1), Asyncs.constant(2)));
}
@Test
public void parallelFailure() {
assertFailure(Asyncs.parallel(Asyncs.constant(1), Asyncs.failure(new Throwable())));
}
@Test
public void parallelAlwaysSucceed() {
assertSuccessNull(Asyncs.parallel(Arrays.asList(Asyncs.constant(1), Asyncs.failure(new Throwable())), true));
}
@Test
public void emptyParallel() {
assertSuccessNull(Asyncs.parallel());
}
@Test
public void untilSuccess() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
@Override
public Async<Integer> get() {
return Asyncs.<Integer>constant(1);
}
}), 1);
}
@Test
public void untilSuccessException() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
private int myCntr = 0;
@Override
public Async<Integer> get() {
myCntr++;
if (myCntr < 2) {
throw new RuntimeException();
} else {
return Asyncs.constant(myCntr);
}
}
}), 2);
}
@Test
public void untilSuccessWithFailures() {
assertSuccess(Asyncs.untilSuccess(new Supplier<Async<Integer>>() {
private int myCounter;
@Override
public Async<Integer> get() {
if (myCounter++ < 10) {
return Asyncs.failure(new RuntimeException());
}
return Asyncs.constant(1);
}
}), 1);
}
@Test
public void succeededTrue() {
assertTrue(Asyncs.isSucceeded(Asyncs.constant(239)));
}
@Test
public void succeededFalse() {
SimpleAsync<Integer> async = new SimpleAsync<>();
assertFalse(Asyncs.isSucceeded(async));
}
private void assertFailure(Async<?> async) {
final Value<Boolean> called = new Value<>(false);
async.onFailure(new Handler<Throwable>() {
@Override
public void handle(Throwable item) {
called.set(true);
}
});
assertTrue(called.get());
}
private <ValueT> void assertSuccess(Async<ValueT> async, ValueT value) {
if (value == null) {
throw new IllegalStateException();
}
final Value<ValueT> result = new Value<>();
async.onSuccess(new Handler<ValueT>() {
@Override
public void handle(ValueT item) {
result.set(item);
}
});
assertEquals(result.get(), value);
}
private <ValueT> void assertSuccessNull(Async<ValueT> async) {
final Value<Object> result = new Value<>(new Object());
async.onSuccess(new Handler<ValueT>() {
@Override
public void handle(ValueT item) {
result.set(item);
}
});
assertNull(result.get());
}
} | add tests for Asyncs.isFailed()
| util/base/src/test/java/jetbrains/jetpad/base/AsyncsTest.java | add tests for Asyncs.isFailed() | <ide><path>til/base/src/test/java/jetbrains/jetpad/base/AsyncsTest.java
<ide> assertFalse(Asyncs.isSucceeded(async));
<ide> }
<ide>
<add> @Test
<add> public void failedTrue() {
<add> assertTrue(Asyncs.isFailed(Asyncs.failure(new RuntimeException())));
<add> }
<add>
<add> @Test
<add> public void failedFalse() {
<add> assertFalse(Asyncs.isFailed(Asyncs.constant(null)));
<add> }
<add>
<ide> private void assertFailure(Async<?> async) {
<ide> final Value<Boolean> called = new Value<>(false);
<ide> async.onFailure(new Handler<Throwable>() { |
|
JavaScript | agpl-3.0 | 43bda7289b17da03d4b8bd43961389649bb5f666 | 0 | utunga/Tradeify,utunga/Tradeify |
function TradeifyWidget(offers_selector, current_tags_selector) {
var offers;
var offers_render_fn;
var current_tags;
var offers_uri;
var map;
/*
google.maps.Map.prototype.markers = new Array();
google.maps.Map.prototype.getMarkers = function() {
return this.markers
};
google.maps.Map.prototype.clearMarkers = function() {
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
this.markers = new Array();
};
google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;
google.maps.Marker.prototype.setMap = function(map) {
if (map) {
map.markers[map.markers.length] = this;
}
this._setMap(map);
};
*/
var offers_directives = {
'div.offer': {
'offer <- messages': {
'a.username@href': 'offer.user.more_info_url',
'a.avatar@href': 'offer.user.more_info_url',
'a.username': 'offer.user.screen_name',
'.avatar img@src': 'offer.user.profile_pic_url',
'.msg .text': 'offer.offer_text',
'span.tags': {
'tag <- offer.tags': {
'a': 'tag.tag',
'+a@class': 'tag.type'
}
},
'.when': 'offer.date'
}
}
};
var map_directives = {
'div.map_offer': {
'map_offer <- messages': {
'a.map_username@href': 'map_offer.user.more_info_url',
'a.map_username': 'map_offer.user.screen_name',
'.map_avatar img@src': 'map_offer.user.profile_pic_url',
'.map_msg .map_text': 'map_offer.offer_text',
'span.map_tags': {
'map_tag <- map_offer.tags': {
'a': 'map_tag.tag',
'+a@class': 'map_tag.type'
}
},
'.map_when': 'map_offer.date'
}
}
};
function updateMap() {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("offer_map"), myOptions);
//map.clearMarkers();
var latlng = new Array();
$.each(offers, function() {
var post = new google.maps.LatLng(this.offer_latitude, this.offer_longitude);
latlng.push(post);
var title = this.offer_address; //this.offer_text + " " + this.user.more_info_url;
var tags = new Array();
$.each(this.tags,function(){
if(this.type=="loc")tags.push(this);
});
var marker = new google.maps.Marker({
clickable: true,
title: title,
position: post,
map: map,
tags: tags
});
google.maps.event.addListener(marker, "click", function() {
createPopup(map, marker);
});
});
var latlngbounds = new google.maps.LatLng();
for (var i = 0; i < latlng.length; i++) {
latlngbounds.extend(latlng[i]);
}
map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
}
var map_popup = $("#map_popup" + ' .map_template').compile(map_directives);
$("#map_popup" + ' .map_template').hide();
function createPopup(map, marker) {
var tags_backup = current_tags.tags.concat(marker.tags);
/*
current_tags.tags.slice();
$.each(marker.tags,function{
var tag = new Tag();
tag.type = "loc";
tag.text = marker.title;
tags_backup.push(tag);
});
*/
var json_url = build_search_query(offers_uri, tags_backup);
$.getJSON(json_url, function(raw_data) {
$("#map_popup" + ' .map_template').render(raw_data, map_popup);
//$("#map_offer_template").quickPager({ pageSize: 2},"#pager");
var infowindow = new google.maps.InfoWindow(
{
content: $("#map_popup").html()
});
$("#map_popup" + ' .map_template').hide();
infowindow.open(map, marker);
});
}
var init = function() {
$("#results").tabs({
//event: 'mouseover'
fx: { height: 'toggle', opacity: 'toggle' },
show: function(event, ui) {
if (ui.panel.id == "results-2") {
$(ui.panel).css("height", "100%");
updateMap();
// map.checkResize();
}
}
});
offers_uri = container.offers_uri;
//compile to a function as soon as possible (ie in 'constructor')
offers_render_fn = $(offers_selector + ' .template').compile(offers_directives);
current_tags = new Tags(current_tags_selector);
current_tags.tag_click(function() {
remove_filter($(this).text());
return false;
});
//update_offers();
}
function offers_(onCompletion){
var json_url = build_search_query(offers_uri);
$.getJSON(json_url, function(data) {
$(offers_selector + ' .template').render(data, offers_render_fn);
$(offers_selector + ' .tags a').click(function() {
//add a filter when tags under a message are clicked
add_filter($(this).text(), $(this).css());
});
onCompletion(data);
});
}
var update_offers = function() {
offers_(function(data) {
offers = data.messages;
updateMap();
$("#offer_template").quickPager({ pageSize: 4 }, "#pager");
});
//$("#results").tabs();
};
var add_filter = function(tag_text, tag_type) {
current_tags.add_tag(tag_text, tag_type);
update_offers();
};
var remove_filter = function(tag_text) {
current_tags.remove_tag(tag_text);
update_offers();
};
var add_fixed_filter = function(tag_text, tag_type) {
current_tags.add_fixed_tag(tag_text, tag_type, false);
update_offers();
};
var build_search_query = function(baseUrl) {
var query = "";
var current_tags_array = (arguments.length > 1) ? arguments[1] : current_tags.tags;
for (tag in current_tags_array) {
if (query != "")
query = query + "&";
query = query + "tag=" + current_tags_array[tag].tag;
}
return baseUrl + "?" + query + "&jsoncallback=?";
};
init();
/* 'public' methods */
this.update_offers = update_offers;
this.add_filter = add_filter;
this.add_fixed_filter = add_fixed_filter;
this.get_fixed_tags = function(){
return current_tags.get_fixed_tags();
}
this.get_offers = function() {
return offers;
}
}
| twademe/osocial/widget_support.js |
function TradeifyWidget(offers_selector, current_tags_selector) {
var offers;
var offers_render_fn;
var current_tags;
var offers_uri;
var map;
/*
google.maps.Map.prototype.markers = new Array();
google.maps.Map.prototype.getMarkers = function() {
return this.markers
};
google.maps.Map.prototype.clearMarkers = function() {
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
this.markers = new Array();
};
google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;
google.maps.Marker.prototype.setMap = function(map) {
if (map) {
map.markers[map.markers.length] = this;
}
this._setMap(map);
};
*/
var offers_directives = {
'div.offer': {
'offer <- messages': {
'a.username@href': 'offer.user.more_info_url',
'a.avatar@href': 'offer.user.more_info_url',
'a.username': 'offer.user.screen_name',
'.avatar img@src': 'offer.user.profile_pic_url',
'.msg .text': 'offer.offer_text',
'span.tags': {
'tag <- offer.tags': {
'a': 'tag.tag',
'+a@class': 'tag.type'
}
},
'.when': 'offer.date'
}
}
};
var map_directives = {
'div.map_offer': {
'map_offer <- messages': {
'a.map_username@href': 'map_offer.user.more_info_url',
'a.map_username': 'map_offer.user.screen_name',
'.map_avatar img@src': 'map_offer.user.profile_pic_url',
'.map_msg .map_text': 'map_offer.offer_text',
'span.map_tags': {
'map_tag <- map_offer.tags': {
'a': 'map_tag.tag',
'+a@class': 'map_tag.type'
}
},
'.map_when': 'map_offer.date'
}
}
};
function updateMap() {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("offer_map"), myOptions);
//map.clearMarkers();
var latlng = new Array();
$.each(offers, function() {
var post = new google.maps.LatLng(this.offer_latitude, this.offer_longitude);
latlng.push(post);
var title = this.offer_address; //this.offer_text + " " + this.user.more_info_url;
var tags = new Array();
$.each(this.tags,function(){
if(this.type=="loc")tags.push(this);
});
var marker = new google.maps.Marker({
clickable: true,
title: title,
position: post,
map: map,
tags: tags
});
google.maps.event.addListener(marker, "click", function() {
createPopup(map, marker);
});
});
var latlngbounds = new GLatLngBounds();
for (var i = 0; i < latlng.length; i++) {
latlngbounds.extend(latlng[i]);
}
map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
}
var map_popup = $("#map_popup" + ' .map_template').compile(map_directives);
$("#map_popup" + ' .map_template').hide();
function createPopup(map, marker) {
var tags_backup = current_tags.tags.concat(marker.tags);
/*
current_tags.tags.slice();
$.each(marker.tags,function{
var tag = new Tag();
tag.type = "loc";
tag.text = marker.title;
tags_backup.push(tag);
});
*/
var json_url = build_search_query(offers_uri, tags_backup);
$.getJSON(json_url, function(raw_data) {
$("#map_popup" + ' .map_template').render(raw_data, map_popup);
//$("#map_offer_template").quickPager({ pageSize: 2},"#pager");
var infowindow = new google.maps.InfoWindow(
{
content: $("#map_popup").html()
});
$("#map_popup" + ' .map_template').hide();
infowindow.open(map, marker);
});
}
var init = function() {
$("#results").tabs({
//event: 'mouseover'
fx: { height: 'toggle', opacity: 'toggle' },
show: function(event, ui) {
if (ui.panel.id == "results-2") {
$(ui.panel).css("height", "100%");
updateMap();
// map.checkResize();
}
}
});
offers_uri = container.offers_uri;
//compile to a function as soon as possible (ie in 'constructor')
offers_render_fn = $(offers_selector + ' .template').compile(offers_directives);
current_tags = new Tags(current_tags_selector);
current_tags.tag_click(function() {
remove_filter($(this).text());
return false;
});
//update_offers();
}
function offers_(onCompletion){
var json_url = build_search_query(offers_uri);
$.getJSON(json_url, function(data) {
$(offers_selector + ' .template').render(data, offers_render_fn);
$(offers_selector + ' .tags a').click(function() {
//add a filter when tags under a message are clicked
add_filter($(this).text(), $(this).css());
});
onCompletion(data);
});
}
var update_offers = function() {
offers_(function(data) {
offers = data.messages;
updateMap();
$("#offer_template").quickPager({ pageSize: 4 }, "#pager");
});
//$("#results").tabs();
};
var add_filter = function(tag_text, tag_type) {
current_tags.add_tag(tag_text, tag_type);
update_offers();
};
var remove_filter = function(tag_text) {
current_tags.remove_tag(tag_text);
update_offers();
};
var add_fixed_filter = function(tag_text, tag_type) {
current_tags.add_fixed_tag(tag_text, tag_type, false);
update_offers();
};
var build_search_query = function(baseUrl) {
var query = "";
var current_tags_array = (arguments.length > 1) ? arguments[1] : current_tags.tags;
for (tag in current_tags_array) {
if (query != "")
query = query + "&";
query = query + "tag=" + current_tags_array[tag].tag;
}
return baseUrl + "?" + query + "&jsoncallback=?";
};
init();
/* 'public' methods */
this.update_offers = update_offers;
this.add_filter = add_filter;
this.add_fixed_filter = add_fixed_filter;
this.get_fixed_tags = function(){
return current_tags.get_fixed_tags();
}
this.get_offers = function() {
return offers;
}
}
| tryed to centre map zoom on markers 3
| twademe/osocial/widget_support.js | tryed to centre map zoom on markers 3 | <ide><path>wademe/osocial/widget_support.js
<ide> createPopup(map, marker);
<ide> });
<ide> });
<del> var latlngbounds = new GLatLngBounds();
<add> var latlngbounds = new google.maps.LatLng();
<ide> for (var i = 0; i < latlng.length; i++) {
<ide> latlngbounds.extend(latlng[i]);
<ide> } |
|
Java | apache-2.0 | c608a089787456e607709f3baef7a3c1622f7bf5 | 0 | east119/zxing,Peter32/zxing,wirthandrel/zxing,DONIKAN/zxing,Solvoj/zxing,0111001101111010/zxing,RatanPaul/zxing,kyosho81/zxing,wanjingyan001/zxing,JerryChin/zxing,qianchenglenger/zxing,zootsuitbrian/zxing,ForeverLucky/zxing,tanelihuuskonen/zxing,peterdocter/zxing,zootsuitbrian/zxing,sunil1989/zxing,OnecloudVideo/zxing,YongHuiLuo/zxing,zilaiyedaren/zxing,erbear/zxing,MonkeyZZZZ/Zxing,wanjingyan001/zxing,Matrix44/zxing,WB-ZZ-TEAM/zxing,ssakitha/sakisolutions,FloatingGuy/zxing,keqingyuan/zxing,MonkeyZZZZ/Zxing,nickperez1285/zxing,lijian17/zxing,Akylas/zxing,l-dobrev/zxing,danielZhang0601/zxing,Akylas/zxing,Akylas/zxing,qingsong-xu/zxing,andyao/zxing,1shawn/zxing,Luise-li/zxing,graug/zxing,east119/zxing,iris-iriswang/zxing,BraveAction/zxing,slayerlp/zxing,liboLiao/zxing,gank0326/zxing,HiWong/zxing,roudunyy/zxing,zzhui1988/zxing,Matrix44/zxing,ChanJLee/zxing,Akylas/zxing,angrilove/zxing,shixingxing/zxing,whycode/zxing,juoni/zxing,Kabele/zxing,ssakitha/sakisolutions,zxing/zxing,zhangyihao/zxing,kailIII/zxing,ChristingKim/zxing,finch0219/zxing,hgl888/zxing,GeorgeMe/zxing,hiagodotme/zxing,peterdocter/zxing,YLBFDEV/zxing,praveen062/zxing,bestwpw/zxing,catalindavid/zxing,GeekHades/zxing,Kevinsu917/zxing,zjcscut/zxing,Matrix44/zxing,jianwoo/zxing,peterdocter/zxing,ptrnov/zxing,1yvT0s/zxing,zzhui1988/zxing,huihui4045/zxing,manl1100/zxing,befairyliu/zxing,andyshao/zxing,loaf/zxing,sysujzh/zxing,wangjun/zxing,ikenneth/zxing,irfanah/zxing,bestwpw/zxing,easycold/zxing,sunil1989/zxing,peterdocter/zxing,917386389/zxing,ZhernakovMikhail/zxing,shwethamallya89/zxing,ouyangkongtong/zxing,huangsongyan/zxing,ikenneth/zxing,JasOXIII/zxing,lvbaosong/zxing,DavidLDawes/zxing,liuchaoya/zxing,meixililu/zxing,GeekHades/zxing,graug/zxing,slayerlp/zxing,tks-dp/zxing,liboLiao/zxing,daverix/zxing,Yi-Kun/zxing,mig1098/zxing,DONIKAN/zxing,Solvoj/zxing,SriramRamesh/zxing,yuanhuihui/zxing,t123yh/zxing,andyao/zxing,eddyb/zxing,ren545457803/zxing,irfanah/zxing,joni1408/zxing,daverix/zxing,micwallace/webscanner,FloatingGuy/zxing,wangjun/zxing,layeka/zxing,zootsuitbrian/zxing,ctoliver/zxing,loaf/zxing,roudunyy/zxing,yuanhuihui/zxing,allenmo/zxing,TestSmirk/zxing,fhchina/zxing,10045125/zxing,peterdocter/zxing,manl1100/zxing,zilaiyedaren/zxing,danielZhang0601/zxing,allenmo/zxing,mayfourth/zxing,krishnanMurali/zxing,jianwoo/zxing,ssakitha/QR-Code-Reader,wangxd1213/zxing,easycold/zxing,peterdocter/zxing,roadrunner1987/zxing,rustemferreira/zxing-projectx,qingsong-xu/zxing,finch0219/zxing,cnbin/zxing,zootsuitbrian/zxing,OnecloudVideo/zxing,reidwooten99/zxing,saif-hmk/zxing,daverix/zxing,freakynit/zxing,1shawn/zxing,hiagodotme/zxing,cncomer/zxing,zootsuitbrian/zxing,roadrunner1987/zxing,micwallace/webscanner,shixingxing/zxing,krishnanMurali/zxing,eight-pack-abdominals/ZXing,micwallace/webscanner,zootsuitbrian/zxing,bittorrent/zxing,rustemferreira/zxing-projectx,mecury/zxing,TestSmirk/zxing,geeklain/zxing,WB-ZZ-TEAM/zxing,JerryChin/zxing,freakynit/zxing,Matrix44/zxing,erbear/zxing,bittorrent/zxing,mecury/zxing,kharohiy/zxing,0111001101111010/zxing,kharohiy/zxing,todotobe1/zxing,eight-pack-abdominals/ZXing,SriramRamesh/zxing,liuchaoya/zxing,praveen062/zxing,lvbaosong/zxing,1yvT0s/zxing,zonamovil/zxing,tanelihuuskonen/zxing,wangxd1213/zxing,qianchenglenger/zxing,huangzl233/zxing,catalindavid/zxing,ssakitha/QR-Code-Reader,daverix/zxing,shwethamallya89/zxing,ren545457803/zxing,l-dobrev/zxing,irwinai/zxing,cncomer/zxing,t123yh/zxing,meixililu/zxing,zjcscut/zxing,Akylas/zxing,kailIII/zxing,fhchina/zxing,juoni/zxing,YuYongzhi/zxing,projectocolibri/zxing,wangdoubleyan/zxing,917386389/zxing,wirthandrel/zxing,lijian17/zxing,reidwooten99/zxing,whycode/zxing,huopochuan/zxing,nickperez1285/zxing,ouyangkongtong/zxing,hgl888/zxing,geeklain/zxing,sysujzh/zxing,layeka/zxing,ForeverLucky/zxing,Peter32/zxing,zhangyihao/zxing,peterdocter/zxing,YuYongzhi/zxing,Fedhaier/zxing,0111001101111010/zxing,0111001101111010/zxing,Akylas/zxing,kyosho81/zxing,cnbin/zxing,peterdocter/zxing,angrilove/zxing,menglifei/zxing,Akylas/zxing,sitexa/zxing,mayfourth/zxing,Fedhaier/zxing,ChanJLee/zxing,ale13jo/zxing,BraveAction/zxing,todotobe1/zxing,saif-hmk/zxing,menglifei/zxing,Yi-Kun/zxing,ale13jo/zxing,ZhernakovMikhail/zxing,Luise-li/zxing,HiWong/zxing,keqingyuan/zxing,YLBFDEV/zxing,zonamovil/zxing,irwinai/zxing,mig1098/zxing,eddyb/zxing,huangzl233/zxing,YongHuiLuo/zxing,DavidLDawes/zxing,huangsongyan/zxing,Kabele/zxing,ctoliver/zxing,tks-dp/zxing,GeorgeMe/zxing,huihui4045/zxing,RatanPaul/zxing,JasOXIII/zxing,joni1408/zxing,ptrnov/zxing,ChristingKim/zxing,projectocolibri/zxing,wangdoubleyan/zxing,sitexa/zxing,befairyliu/zxing,Kevinsu917/zxing,geeklain/zxing,zootsuitbrian/zxing,huopochuan/zxing,andyshao/zxing,daverix/zxing,iris-iriswang/zxing,zxing/zxing | /*
* Copyright (C) 2010 ZXing 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 com.google.zxing.client.android;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
/**
* Manages beeps and vibrations for {@link CaptureActivity}.
*/
final class BeepManager implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
private static final String TAG = BeepManager.class.getSimpleName();
private static final float BEEP_VOLUME = 0.10f;
private static final long VIBRATE_DURATION = 200L;
private final Activity activity;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private boolean vibrate;
BeepManager(Activity activity) {
this.activity = activity;
this.mediaPlayer = null;
updatePrefs();
}
synchronized void updatePrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
playBeep = shouldBeep(prefs, activity);
vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
// so we now play on the music stream.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = buildMediaPlayer(activity);
}
}
synchronized void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
private static boolean shouldBeep(SharedPreferences prefs, Context activity) {
boolean shouldPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
if (shouldPlayBeep) {
// See if sound settings overrides this
AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;
}
}
return shouldPlayBeep;
}
private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
@Override
public void onCompletion(MediaPlayer mp) {
// When the beep has finished playing, rewind to queue up another one.
mp.seekTo(0);
}
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
// we are finished, so put up an appropriate error toast if required and finish
activity.finish();
} else {
// possibly media player error, so release and recreate
mp.release();
mediaPlayer = null;
updatePrefs();
}
return true;
}
}
| android/src/com/google/zxing/client/android/BeepManager.java | /*
* Copyright (C) 2010 ZXing 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 com.google.zxing.client.android;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
/**
* Manages beeps and vibrations for {@link CaptureActivity}.
*/
final class BeepManager {
private static final String TAG = BeepManager.class.getSimpleName();
private static final float BEEP_VOLUME = 0.10f;
private static final long VIBRATE_DURATION = 200L;
private final Activity activity;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private boolean vibrate;
BeepManager(Activity activity) {
this.activity = activity;
this.mediaPlayer = null;
updatePrefs();
}
void updatePrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
playBeep = shouldBeep(prefs, activity);
vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
// so we now play on the music stream.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = buildMediaPlayer(activity);
}
}
void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
private static boolean shouldBeep(SharedPreferences prefs, Context activity) {
boolean shouldPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
if (shouldPlayBeep) {
// See if sound settings overrides this
AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;
}
}
return shouldPlayBeep;
}
private static MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// When the beep has finished playing, rewind to queue up another one.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer player) {
player.seekTo(0);
}
});
AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
}
| Issue 1680 Finish / clean up media player in rare case the media server dies
git-svn-id: b10e9e05a96f28f96949e4aa4212c55f640c8f96@2799 59b500cc-1b3d-0410-9834-0bbf25fbcc57
| android/src/com/google/zxing/client/android/BeepManager.java | Issue 1680 Finish / clean up media player in rare case the media server dies | <ide><path>ndroid/src/com/google/zxing/client/android/BeepManager.java
<ide> /**
<ide> * Manages beeps and vibrations for {@link CaptureActivity}.
<ide> */
<del>final class BeepManager {
<add>final class BeepManager implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
<ide>
<ide> private static final String TAG = BeepManager.class.getSimpleName();
<ide>
<ide> updatePrefs();
<ide> }
<ide>
<del> void updatePrefs() {
<add> synchronized void updatePrefs() {
<ide> SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
<ide> playBeep = shouldBeep(prefs, activity);
<ide> vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
<ide> }
<ide> }
<ide>
<del> void playBeepSoundAndVibrate() {
<add> synchronized void playBeepSoundAndVibrate() {
<ide> if (playBeep && mediaPlayer != null) {
<ide> mediaPlayer.start();
<ide> }
<ide> return shouldPlayBeep;
<ide> }
<ide>
<del> private static MediaPlayer buildMediaPlayer(Context activity) {
<add> private MediaPlayer buildMediaPlayer(Context activity) {
<ide> MediaPlayer mediaPlayer = new MediaPlayer();
<ide> mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
<del> // When the beep has finished playing, rewind to queue up another one.
<del> mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
<del> @Override
<del> public void onCompletion(MediaPlayer player) {
<del> player.seekTo(0);
<del> }
<del> });
<add> mediaPlayer.setOnCompletionListener(this);
<add> mediaPlayer.setOnErrorListener(this);
<ide>
<ide> AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
<ide> try {
<ide> return mediaPlayer;
<ide> }
<ide>
<add> @Override
<add> public void onCompletion(MediaPlayer mp) {
<add> // When the beep has finished playing, rewind to queue up another one.
<add> mp.seekTo(0);
<add> }
<add>
<add> @Override
<add> public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
<add> if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
<add> // we are finished, so put up an appropriate error toast if required and finish
<add> activity.finish();
<add> } else {
<add> // possibly media player error, so release and recreate
<add> mp.release();
<add> mediaPlayer = null;
<add> updatePrefs();
<add> }
<add> return true;
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 8b1cfe62ce02c00c3f305dc55c3543a579cf99c8 | 0 | wildfly-security/wildfly-elytron,wildfly-security/wildfly-elytron | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.http.impl;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.wildfly.common.Assert.checkNotNullParam;
import static org.wildfly.security._private.ElytronMessages.log;
import static org.wildfly.security.http.HttpConstants.AUTHORIZATION;
import static org.wildfly.security.http.HttpConstants.CONFIG_GSS_MANAGER;
import static org.wildfly.security.http.HttpConstants.FORBIDDEN;
import static org.wildfly.security.http.HttpConstants.NEGOTIATE;
import static org.wildfly.security.http.HttpConstants.SPNEGO_NAME;
import static org.wildfly.security.http.HttpConstants.UNAUTHORIZED;
import static org.wildfly.security.http.HttpConstants.WWW_AUTHENTICATE;
import static org.wildfly.security.http.HttpConstants.CONFIG_STATE_SCOPES;
import java.io.IOException;
import java.io.Serializable;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.sasl.AuthorizeCallback;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.wildfly.security.auth.callback.AuthenticationCompleteCallback;
import org.wildfly.security.auth.callback.CachedIdentityAuthorizeCallback;
import org.wildfly.security.auth.callback.IdentityCredentialCallback;
import org.wildfly.security.auth.callback.ServerCredentialCallback;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.cache.CachedIdentity;
import org.wildfly.security.cache.IdentityCache;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpServerAuthenticationMechanism;
import org.wildfly.security.http.HttpServerRequest;
import org.wildfly.security.http.HttpServerResponse;
import org.wildfly.security.http.Scope;
import org.wildfly.security.mechanism.AuthenticationMechanismException;
import org.wildfly.security.mechanism.MechanismUtil;
import org.wildfly.security.util.ByteIterator;
import org.wildfly.security.util._private.Arrays2;
/**
* A {@link HttpServerAuthenticationMechanism} implementation to support SPNEGO.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
public class SpnegoAuthenticationMechanism implements HttpServerAuthenticationMechanism {
private static final String CHALLENGE_PREFIX = NEGOTIATE + " ";
private static final String SPNEGO_CONTEXT_KEY = SpnegoAuthenticationMechanism.class.getName() + ".spnego-context";
private static final String CACHED_IDENTITY_KEY = SpnegoAuthenticationMechanism.class.getName() + ".elytron-identity";
private static final byte[] NEG_STATE_REJECT = new byte[] { (byte) 0xA1, 0x07, 0x30, 0x05, (byte) 0xA0, 0x03, 0x0A, 0x01, 0x02 };
private final CallbackHandler callbackHandler;
private final GSSManager gssManager;
private final Scope[] storageScopes;
SpnegoAuthenticationMechanism(final CallbackHandler callbackHandler, final Map<String, ?> properties) {
checkNotNullParam("callbackHandler", callbackHandler);
checkNotNullParam("properties", properties);
this.callbackHandler = callbackHandler;
this.gssManager = properties.containsKey(CONFIG_GSS_MANAGER) ? (GSSManager) properties.get(CONFIG_GSS_MANAGER) : GSSManager.getInstance();
String scopesProperty = (String) properties.get(CONFIG_STATE_SCOPES);
if (scopesProperty == null) {
storageScopes = new Scope[] { Scope.SESSION, Scope.CONNECTION };
} else {
String[] names = scopesProperty.split(",");
storageScopes = new Scope[names.length];
for (int i=0;i<names.length;i++) {
if ("NONE".equals(names[i])) {
storageScopes[i] = null;
} else {
Scope scope = Scope.valueOf(names[i]);
if (scope == Scope.APPLICATION || scope == Scope.GLOBAL) {
throw log.unsuitableScope(scope.name());
}
storageScopes[i] = scope;
}
}
}
}
@Override
public String getMechanismName() {
return SPNEGO_NAME;
}
@Override
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
HttpScope storageScope = getStorageScope(request);
IdentityCache identityCache = null;
identityCache = createIdentityCache(identityCache, storageScope, false);
if (identityCache != null && attemptReAuthentication(identityCache, request)) {
log.trace("Successfully authorized using cached identity");
return;
}
// If the scope does not already exist it can't have previously been used to store state.
SpnegoContext spnegoContext = storageScope != null && storageScope.exists() ? storageScope.getAttachment(SPNEGO_CONTEXT_KEY, SpnegoContext.class) : null;
GSSContext gssContext = spnegoContext != null ? spnegoContext.gssContext : null;
KerberosTicket kerberosTicket = spnegoContext != null ? spnegoContext.kerberosTicket : null;
log.tracef("Evaluating SPNEGO request: cached GSSContext = %s", gssContext);
// Do we already have a cached identity? If so use it.
if (gssContext != null && gssContext.isEstablished()) {
identityCache = createIdentityCache(identityCache, storageScope, true);
if (authorizeSrcName(gssContext, identityCache)) {
log.trace("Successfully authorized using cached GSSContext");
request.authenticationComplete();
return;
} else {
clearAttachments(storageScope);
gssContext = null;
kerberosTicket = null;
}
}
if (gssContext == null) { // init GSSContext
if (spnegoContext == null) {
spnegoContext = new SpnegoContext();
}
ServerCredentialCallback gssCredentialCallback = new ServerCredentialCallback(GSSKerberosCredential.class);
final GSSCredential serviceGssCredential;
try {
log.trace("Obtaining GSSCredential for the service from callback handler...");
callbackHandler.handle(new Callback[] { gssCredentialCallback });
serviceGssCredential = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getGssCredential);
kerberosTicket = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getKerberosTicket);
} catch (IOException | UnsupportedCallbackException e) {
throw log.mechCallbackHandlerFailedForUnknownReason(SPNEGO_NAME, e).toHttpAuthenticationException();
}
if (serviceGssCredential == null) {
throw log.unableToObtainServerCredential(SPNEGO_NAME).toHttpAuthenticationException();
}
try {
gssContext = gssManager.createContext(serviceGssCredential);
if (log.isTraceEnabled()) {
log.tracef("Using SpnegoAuthenticationMechanism to authenticate %s using the following mechanisms: [%s]",
serviceGssCredential.getName(), Arrays2.objectToString(serviceGssCredential.getMechs()));
}
} catch (GSSException e) {
throw log.mechUnableToCreateGssContext(SPNEGO_NAME, e).toHttpAuthenticationException();
}
spnegoContext.gssContext = gssContext;
spnegoContext.kerberosTicket = kerberosTicket;
}
// authentication exchange
List<String> authorizationValues = request.getRequestHeaderValues(AUTHORIZATION);
Optional<String> challenge = authorizationValues != null ? authorizationValues.stream()
.filter(s -> s.startsWith(CHALLENGE_PREFIX)).limit(1).map(s -> s.substring(CHALLENGE_PREFIX.length()))
.findFirst() : Optional.empty();
if (log.isTraceEnabled()) {
log.tracef("Sent HTTP authorizations: [%s]", Arrays2.objectToString(authorizationValues));
}
// Do we have an incoming response to a challenge? If so, process it.
if (challenge.isPresent()) {
log.trace("Processing incoming response to a challenge...");
// We only need to store the scope if we have a challenge otherwise the next round
// trip will be a new response anyway.
if (storageScope != null && (storageScope.exists() || storageScope.create())) {
log.tracef("Caching SPNEGO Context with GSSContext %s and KerberosTicket %s", gssContext, kerberosTicket);
storageScope.setAttachment(SPNEGO_CONTEXT_KEY, spnegoContext);
} else {
storageScope = null;
log.trace("No usable HttpScope for storage, continuation will not be possible");
}
byte[] decodedValue = ByteIterator.ofBytes(challenge.get().getBytes(UTF_8)).base64Decode().drain();
Subject subject = new Subject(true, Collections.emptySet(), Collections.emptySet(), kerberosTicket != null ? Collections.singleton(kerberosTicket) : Collections.emptySet());
byte[] responseToken;
try {
final GSSContext finalGssContext = gssContext;
responseToken = Subject.doAs(subject, (PrivilegedExceptionAction<byte[]>) () -> finalGssContext.acceptSecContext(decodedValue, 0, decodedValue.length));
} catch (PrivilegedActionException e) {
log.trace("Call to acceptSecContext failed.", e.getCause());
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
return;
}
if (gssContext.isEstablished()) { // no more tokens are needed from the peer
final GSSCredential gssCredential;
try {
gssCredential = gssContext.getCredDelegState() ? gssContext.getDelegCred() : null;
} catch (GSSException e) {
log.trace("Unable to access delegated credential despite being delegated.", e);
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
return;
}
if (gssCredential != null) {
log.trace("Associating delegated GSSCredential with identity.");
handleCallback(new IdentityCredentialCallback(new GSSKerberosCredential(gssCredential), true));
} else {
log.trace("No GSSCredential delegated from client.");
}
log.trace("GSSContext established, authorizing...");
identityCache = createIdentityCache(identityCache, storageScope, true);
if (authorizeSrcName(gssContext, identityCache)) {
log.trace("GSSContext established and authorized - authentication complete");
request.authenticationComplete(
responseToken == null ? null : response -> sendChallenge(responseToken, response, 0));
} else {
log.trace("Authorization of established GSSContext failed");
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
}
} else if (Arrays.equals(responseToken, NEG_STATE_REJECT)) {
// for IBM java - prevent sending UNAUTHORIZED for [negState = reject] token
log.trace("GSSContext failed - sending negotiation rejected to the peer");
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME),
response -> sendChallenge(responseToken, response, FORBIDDEN));
return;
} else if (responseToken != null && storageScope != null) {
log.trace("GSSContext establishing - sending negotiation token to the peer");
request.authenticationInProgress(response -> sendChallenge(responseToken, response, UNAUTHORIZED));
} else {
log.trace("GSSContext establishing - unable to hold GSSContext so continuation will not be possible");
handleCallback(AuthenticationCompleteCallback.FAILED);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
}
} else {
log.trace("Request lacks valid authentication credentials");
clearAttachments(storageScope);
request.noAuthenticationInProgress(this::sendBareChallenge);
}
}
private HttpScope getStorageScope(HttpServerRequest request) throws HttpAuthenticationException {
for (Scope scope : storageScopes) {
if (scope == null) {
return null;
}
HttpScope httpScope = request.getScope(scope);
if (httpScope != null && httpScope.supportsAttachments()) {
if (log.isTraceEnabled()) {
log.tracef("Using HttpScope '%s' with ID '%s'", scope.name(), httpScope.getID());
}
return httpScope;
} else {
if (log.isTraceEnabled()) {
log.tracef(httpScope == null ? "HttpScope %s not supported" : "HttpScope %s does not support attachments", scope);
}
}
}
throw log.unableToIdentifyHttpScope();
}
private IdentityCache createIdentityCache(final IdentityCache existingCache, final HttpScope httpScope, boolean forUpdate) {
if (existingCache != null || // If we have a cache continue to use it.
httpScope == null || // If we don't have a scope we can't create a cache (existing cache is null so return it)
!httpScope.supportsAttachments() || // It is not null but if it doesn't support attachments pointless to wrap in a cache
(!httpScope.exists() && (!forUpdate || !httpScope.create())) // Doesn't exist and if update is requested can't be created
) {
return existingCache;
}
return new IdentityCache() {
@Override
public CachedIdentity remove() {
CachedIdentity cachedIdentity = get();
httpScope.setAttachment(CACHED_IDENTITY_KEY, null);
return cachedIdentity;
}
@Override
public void put(SecurityIdentity identity) {
httpScope.setAttachment(CACHED_IDENTITY_KEY, new CachedIdentity(SPNEGO_NAME, identity));
}
@Override
public CachedIdentity get() {
return httpScope.getAttachment(CACHED_IDENTITY_KEY, CachedIdentity.class);
}
};
}
private static void clearAttachments(HttpScope scope) {
if (scope != null) {
scope.setAttachment(SPNEGO_CONTEXT_KEY, null); // clear cache
}
}
private void sendBareChallenge(HttpServerResponse response) {
response.addResponseHeader(WWW_AUTHENTICATE, NEGOTIATE);
response.setStatusCode(UNAUTHORIZED);
}
private void sendChallenge(byte[] responseToken, HttpServerResponse response, int statusCode) {
if (log.isTraceEnabled()) {
log.tracef("Sending intermediate challenge: %s", Arrays2.objectToString(responseToken));
}
if (responseToken == null) {
response.addResponseHeader(WWW_AUTHENTICATE, NEGOTIATE);
} else {
String responseConverted = ByteIterator.ofBytes(responseToken).base64Encode().drainToString();
response.addResponseHeader(WWW_AUTHENTICATE, CHALLENGE_PREFIX + responseConverted);
}
if (statusCode != 0) {
response.setStatusCode(statusCode);
}
}
private boolean attemptReAuthentication(IdentityCache identityCache, HttpServerRequest request) throws HttpAuthenticationException {
CachedIdentityAuthorizeCallback authorizeCallback = new CachedIdentityAuthorizeCallback(identityCache);
try {
callbackHandler.handle(new Callback[] { authorizeCallback });
} catch (IOException | UnsupportedCallbackException e) {
throw new HttpAuthenticationException(e);
}
if (authorizeCallback.isAuthorized()) {
try {
handleCallback(AuthenticationCompleteCallback.SUCCEEDED);
} catch (IOException e) {
throw new HttpAuthenticationException(e);
}
request.authenticationComplete(null, identityCache::remove);
return true;
}
return false;
}
private boolean authorizeSrcName(GSSContext gssContext, IdentityCache identityCache) throws HttpAuthenticationException {
final GSSName srcName;
try {
srcName = gssContext.getSrcName();
if (srcName == null) {
log.trace("Authorization failed - srcName of GSSContext (name of initiator) is null - wrong realm or kdc?");
return false;
}
} catch (GSSException e) {
log.trace("Unable to obtain srcName from established GSSContext.", e);
return false;
}
final BooleanSupplier authorizedFunction;
final Callback authorizeCallBack;
if (gssContext.getCredDelegState()) {
try {
GSSCredential credential = gssContext.getDelegCred();
log.tracef("Credential delegation enabled, delegated credential = %s", credential);
MechanismUtil.handleCallbacks(SPNEGO_NAME, callbackHandler, new IdentityCredentialCallback(new GSSKerberosCredential(credential), true));
} catch (UnsupportedCallbackException ignored) {
// ignored
} catch (AuthenticationMechanismException e) {
throw e.toHttpAuthenticationException();
} catch (GSSException e) {
throw new HttpAuthenticationException(e);
}
} else {
log.trace("Credential delegation not enabled");
}
boolean authorized = false;
try {
String clientName = srcName.toString();
if (identityCache != null) {
CachedIdentityAuthorizeCallback cacheCallback = new CachedIdentityAuthorizeCallback(new NamePrincipal(clientName), identityCache, true);
authorizedFunction = cacheCallback::isAuthorized;
authorizeCallBack = cacheCallback;
} else {
AuthorizeCallback plainCallback = new AuthorizeCallback(clientName, clientName);
authorizedFunction = plainCallback::isAuthorized;
authorizeCallBack = plainCallback;
}
callbackHandler.handle(new Callback[] { authorizeCallBack });
authorized = authorizedFunction.getAsBoolean();
log.tracef("Authorized by callback handler = %b clientName = [%s]", authorized, clientName);
} catch (IOException e) {
log.trace("IOException during AuthorizeCallback handling", e);
throw log.mechServerSideAuthenticationFailed(SPNEGO_NAME, e).toHttpAuthenticationException();
} catch (UnsupportedCallbackException ignored) {
}
if (authorized) {
// If we fail the caller may still decide to try and continue authentication.
handleCallback(AuthenticationCompleteCallback.SUCCEEDED);
}
return authorized;
}
private void handleCallback(Callback callback) throws HttpAuthenticationException {
try {
MechanismUtil.handleCallbacks(SPNEGO_NAME, callbackHandler, callback);
} catch (AuthenticationMechanismException e) {
throw e.toHttpAuthenticationException();
} catch (UnsupportedCallbackException ignored) {
}
}
private static class SpnegoContext implements Serializable {
transient GSSContext gssContext;
transient KerberosTicket kerberosTicket;
}
}
| src/main/java/org/wildfly/security/http/impl/SpnegoAuthenticationMechanism.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.http.impl;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.wildfly.common.Assert.checkNotNullParam;
import static org.wildfly.security._private.ElytronMessages.log;
import static org.wildfly.security.http.HttpConstants.AUTHORIZATION;
import static org.wildfly.security.http.HttpConstants.CONFIG_GSS_MANAGER;
import static org.wildfly.security.http.HttpConstants.FORBIDDEN;
import static org.wildfly.security.http.HttpConstants.NEGOTIATE;
import static org.wildfly.security.http.HttpConstants.SPNEGO_NAME;
import static org.wildfly.security.http.HttpConstants.UNAUTHORIZED;
import static org.wildfly.security.http.HttpConstants.WWW_AUTHENTICATE;
import static org.wildfly.security.http.HttpConstants.CONFIG_STATE_SCOPES;
import java.io.IOException;
import java.io.Serializable;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.sasl.AuthorizeCallback;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.wildfly.security.auth.callback.AuthenticationCompleteCallback;
import org.wildfly.security.auth.callback.CachedIdentityAuthorizeCallback;
import org.wildfly.security.auth.callback.IdentityCredentialCallback;
import org.wildfly.security.auth.callback.ServerCredentialCallback;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.cache.CachedIdentity;
import org.wildfly.security.cache.IdentityCache;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpServerAuthenticationMechanism;
import org.wildfly.security.http.HttpServerRequest;
import org.wildfly.security.http.HttpServerResponse;
import org.wildfly.security.http.Scope;
import org.wildfly.security.mechanism.AuthenticationMechanismException;
import org.wildfly.security.mechanism.MechanismUtil;
import org.wildfly.security.util.ByteIterator;
import org.wildfly.security.util._private.Arrays2;
/**
* A {@link HttpServerAuthenticationMechanism} implementation to support SPNEGO.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
public class SpnegoAuthenticationMechanism implements HttpServerAuthenticationMechanism {
private static final String CHALLENGE_PREFIX = NEGOTIATE + " ";
private static final String SPNEGO_CONTEXT_KEY = SpnegoAuthenticationMechanism.class.getName() + ".spnego-context";
private static final String CACHED_IDENTITY_KEY = SpnegoAuthenticationMechanism.class.getName() + ".elytron-identity";
private static final byte[] NEG_STATE_REJECT = new byte[] { (byte) 0xA1, 0x07, 0x30, 0x05, (byte) 0xA0, 0x03, 0x0A, 0x01, 0x02 };
private final CallbackHandler callbackHandler;
private final GSSManager gssManager;
private final Scope[] storageScopes;
SpnegoAuthenticationMechanism(final CallbackHandler callbackHandler, final Map<String, ?> properties) {
checkNotNullParam("callbackHandler", callbackHandler);
checkNotNullParam("properties", properties);
this.callbackHandler = callbackHandler;
this.gssManager = properties.containsKey(CONFIG_GSS_MANAGER) ? (GSSManager) properties.get(CONFIG_GSS_MANAGER) : GSSManager.getInstance();
String scopesProperty = (String) properties.get(CONFIG_STATE_SCOPES);
if (scopesProperty == null) {
storageScopes = new Scope[] { Scope.SESSION, Scope.CONNECTION };
} else {
String[] names = scopesProperty.split(",");
storageScopes = new Scope[names.length];
for (int i=0;i<names.length;i++) {
if ("NONE".equals(names[i])) {
storageScopes[i] = null;
} else {
Scope scope = Scope.valueOf(names[i]);
if (scope == Scope.APPLICATION || scope == Scope.GLOBAL) {
throw log.unsuitableScope(scope.name());
}
storageScopes[i] = scope;
}
}
}
}
@Override
public String getMechanismName() {
return SPNEGO_NAME;
}
@Override
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
HttpScope storageScope = getStorageScope(request);
IdentityCache identityCache = null;
identityCache = createIdentityCache(identityCache, storageScope, false);
if (identityCache != null && attemptReAuthentication(identityCache, request)) {
log.trace("Successfully authorized using cached identity");
return;
}
// If the scope does not already exist it can't have previously been used to store state.
SpnegoContext spnegoContext = storageScope != null && storageScope.exists() ? storageScope.getAttachment(SPNEGO_CONTEXT_KEY, SpnegoContext.class) : null;
GSSContext gssContext = spnegoContext != null ? spnegoContext.gssContext : null;
KerberosTicket kerberosTicket = spnegoContext != null ? spnegoContext.kerberosTicket : null;
log.tracef("Evaluating SPNEGO request: cached GSSContext = %s", gssContext);
// Do we already have a cached identity? If so use it.
if (gssContext != null && gssContext.isEstablished()) {
identityCache = createIdentityCache(identityCache, storageScope, true);
if (authorizeSrcName(gssContext, identityCache)) {
log.trace("Successfully authorized using cached GSSContext");
request.authenticationComplete();
return;
} else {
clearAttachments(storageScope);
gssContext = null;
kerberosTicket = null;
}
}
if (gssContext == null) { // init GSSContext
if (spnegoContext == null) {
spnegoContext = new SpnegoContext();
}
ServerCredentialCallback gssCredentialCallback = new ServerCredentialCallback(GSSKerberosCredential.class);
final GSSCredential serviceGssCredential;
try {
log.trace("Obtaining GSSCredential for the service from callback handler...");
callbackHandler.handle(new Callback[] { gssCredentialCallback });
serviceGssCredential = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getGssCredential);
kerberosTicket = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getKerberosTicket);
} catch (IOException | UnsupportedCallbackException e) {
throw log.mechCallbackHandlerFailedForUnknownReason(SPNEGO_NAME, e).toHttpAuthenticationException();
}
if (serviceGssCredential == null) {
throw log.unableToObtainServerCredential(SPNEGO_NAME).toHttpAuthenticationException();
}
try {
gssContext = gssManager.createContext(serviceGssCredential);
if (log.isTraceEnabled()) {
log.tracef("Using SpnegoAuthenticationMechanism to authenticate %s using the following mechanisms: [%s]",
serviceGssCredential.getName(), Arrays2.objectToString(serviceGssCredential.getMechs()));
}
} catch (GSSException e) {
throw log.mechUnableToCreateGssContext(SPNEGO_NAME, e).toHttpAuthenticationException();
}
spnegoContext.gssContext = gssContext;
spnegoContext.kerberosTicket = kerberosTicket;
}
// authentication exchange
List<String> authorizationValues = request.getRequestHeaderValues(AUTHORIZATION);
Optional<String> challenge = authorizationValues != null ? authorizationValues.stream()
.filter(s -> s.startsWith(CHALLENGE_PREFIX)).limit(1).map(s -> s.substring(CHALLENGE_PREFIX.length()))
.findFirst() : Optional.empty();
if (log.isTraceEnabled()) {
log.tracef("Sent HTTP authorizations: [%s]", Arrays2.objectToString(authorizationValues));
}
// Do we have an incoming response to a challenge? If so, process it.
if (challenge.isPresent()) {
log.trace("Processing incoming response to a challenge...");
// We only need to store the scope if we have a challenge otherwise the next round
// trip will be a new response anyway.
if (storageScope != null && (storageScope.exists() || storageScope.create())) {
log.tracef("Caching SPNEGO Context with GSSContext %s and KerberosTicket %s", gssContext, kerberosTicket);
storageScope.setAttachment(SPNEGO_CONTEXT_KEY, spnegoContext);
} else {
storageScope = null;
log.trace("No usable HttpScope for storage, continuation will not be possible");
}
byte[] decodedValue = ByteIterator.ofBytes(challenge.get().getBytes(UTF_8)).base64Decode().drain();
Subject subject = new Subject(true, Collections.emptySet(), Collections.emptySet(), kerberosTicket != null ? Collections.singleton(kerberosTicket) : Collections.emptySet());
byte[] responseToken;
try {
final GSSContext finalGssContext = gssContext;
responseToken = Subject.doAs(subject, (PrivilegedExceptionAction<byte[]>) () -> finalGssContext.acceptSecContext(decodedValue, 0, decodedValue.length));
} catch (PrivilegedActionException e) {
log.trace("Call to acceptSecContext failed.", e.getCause());
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
return;
}
if (gssContext.isEstablished()) {
final GSSCredential gssCredential;
try {
gssCredential = gssContext.getCredDelegState() ? gssContext.getDelegCred() : null;
} catch (GSSException e) {
log.trace("Unable to access delegated credential despite being delegated.", e);
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
return;
}
if (gssCredential != null) {
log.trace("Associating delegated GSSCredential with identity.");
handleCallback(new IdentityCredentialCallback(new GSSKerberosCredential(gssCredential), true));
} else {
log.trace("No GSSCredential delegated from client.");
}
log.trace("GSSContext established, authorizing...");
identityCache = createIdentityCache(identityCache, storageScope, true);
if (authorizeSrcName(gssContext, identityCache)) {
log.trace("GSSContext established and authorized - authentication complete");
request.authenticationComplete(
responseToken == null ? null : response -> sendChallenge(responseToken, response, 0));
} else {
log.trace("Authorization of established GSSContext failed");
handleCallback(AuthenticationCompleteCallback.FAILED);
clearAttachments(storageScope);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME),
responseToken == null ? null : response -> sendChallenge(responseToken, response, FORBIDDEN));
}
} else if (Arrays.equals(responseToken, NEG_STATE_REJECT)) {
// for IBM java - prevent sending UNAUTHORIZED for [negState = reject] token
log.trace("GSSContext failed - sending negotiation rejected to the peer");
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME),
response -> sendChallenge(responseToken, response, FORBIDDEN));
return;
} else if (responseToken != null && storageScope != null) {
log.trace("GSSContext establishing - sending negotiation token to the peer");
request.authenticationInProgress(response -> sendChallenge(responseToken, response, UNAUTHORIZED));
} else {
log.trace("GSSContext establishing - unable to hold GSSContext so continuation will not be possible");
handleCallback(AuthenticationCompleteCallback.FAILED);
request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
}
} else {
log.trace("Request lacks valid authentication credentials");
clearAttachments(storageScope);
request.noAuthenticationInProgress(this::sendBareChallenge);
}
}
private HttpScope getStorageScope(HttpServerRequest request) throws HttpAuthenticationException {
for (Scope scope : storageScopes) {
if (scope == null) {
return null;
}
HttpScope httpScope = request.getScope(scope);
if (httpScope != null && httpScope.supportsAttachments()) {
if (log.isTraceEnabled()) {
log.tracef("Using HttpScope '%s' with ID '%s'", scope.name(), httpScope.getID());
}
return httpScope;
} else {
if (log.isTraceEnabled()) {
log.tracef(httpScope == null ? "HttpScope %s not supported" : "HttpScope %s does not support attachments", scope);
}
}
}
throw log.unableToIdentifyHttpScope();
}
private IdentityCache createIdentityCache(final IdentityCache existingCache, final HttpScope httpScope, boolean forUpdate) {
if (existingCache != null || // If we have a cache continue to use it.
httpScope == null || // If we don't have a scope we can't create a cache (existing cache is null so return it)
!httpScope.supportsAttachments() || // It is not null but if it doesn't support attachments pointless to wrap in a cache
(!httpScope.exists() && (!forUpdate || !httpScope.create())) // Doesn't exist and if update is requested can't be created
) {
return existingCache;
}
return new IdentityCache() {
@Override
public CachedIdentity remove() {
CachedIdentity cachedIdentity = get();
httpScope.setAttachment(CACHED_IDENTITY_KEY, null);
return cachedIdentity;
}
@Override
public void put(SecurityIdentity identity) {
httpScope.setAttachment(CACHED_IDENTITY_KEY, new CachedIdentity(SPNEGO_NAME, identity));
}
@Override
public CachedIdentity get() {
return httpScope.getAttachment(CACHED_IDENTITY_KEY, CachedIdentity.class);
}
};
}
private static void clearAttachments(HttpScope scope) {
if (scope != null) {
scope.setAttachment(SPNEGO_CONTEXT_KEY, null); // clear cache
}
}
private void sendBareChallenge(HttpServerResponse response) {
response.addResponseHeader(WWW_AUTHENTICATE, NEGOTIATE);
response.setStatusCode(UNAUTHORIZED);
}
private void sendChallenge(byte[] responseToken, HttpServerResponse response, int statusCode) {
if (log.isTraceEnabled()) {
log.tracef("Sending intermediate challenge: %s", Arrays2.objectToString(responseToken));
}
if (responseToken == null) {
response.addResponseHeader(WWW_AUTHENTICATE, NEGOTIATE);
} else {
String responseConverted = ByteIterator.ofBytes(responseToken).base64Encode().drainToString();
response.addResponseHeader(WWW_AUTHENTICATE, CHALLENGE_PREFIX + responseConverted);
}
if (statusCode != 0) {
response.setStatusCode(statusCode);
}
}
private boolean attemptReAuthentication(IdentityCache identityCache, HttpServerRequest request) throws HttpAuthenticationException {
CachedIdentityAuthorizeCallback authorizeCallback = new CachedIdentityAuthorizeCallback(identityCache);
try {
callbackHandler.handle(new Callback[] { authorizeCallback });
} catch (IOException | UnsupportedCallbackException e) {
throw new HttpAuthenticationException(e);
}
if (authorizeCallback.isAuthorized()) {
try {
handleCallback(AuthenticationCompleteCallback.SUCCEEDED);
} catch (IOException e) {
throw new HttpAuthenticationException(e);
}
request.authenticationComplete(null, identityCache::remove);
return true;
}
return false;
}
private boolean authorizeSrcName(GSSContext gssContext, IdentityCache identityCache) throws HttpAuthenticationException {
final GSSName srcName;
try {
srcName = gssContext.getSrcName();
if (srcName == null) {
log.trace("Authorization failed - srcName of GSSContext (name of initiator) is null - wrong realm or kdc?");
return false;
}
} catch (GSSException e) {
log.trace("Unable to obtain srcName from established GSSContext.", e);
return false;
}
final BooleanSupplier authorizedFunction;
final Callback authorizeCallBack;
if (gssContext.getCredDelegState()) {
try {
GSSCredential credential = gssContext.getDelegCred();
log.tracef("Credential delegation enabled, delegated credential = %s", credential);
MechanismUtil.handleCallbacks(SPNEGO_NAME, callbackHandler, new IdentityCredentialCallback(new GSSKerberosCredential(credential), true));
} catch (UnsupportedCallbackException ignored) {
// ignored
} catch (AuthenticationMechanismException e) {
throw e.toHttpAuthenticationException();
} catch (GSSException e) {
throw new HttpAuthenticationException(e);
}
} else {
log.trace("Credential delegation not enabled");
}
boolean authorized = false;
try {
String clientName = srcName.toString();
if (identityCache != null) {
CachedIdentityAuthorizeCallback cacheCallback = new CachedIdentityAuthorizeCallback(new NamePrincipal(clientName), identityCache, true);
authorizedFunction = cacheCallback::isAuthorized;
authorizeCallBack = cacheCallback;
} else {
AuthorizeCallback plainCallback = new AuthorizeCallback(clientName, clientName);
authorizedFunction = plainCallback::isAuthorized;
authorizeCallBack = plainCallback;
}
callbackHandler.handle(new Callback[] { authorizeCallBack });
authorized = authorizedFunction.getAsBoolean();
log.tracef("Authorized by callback handler = %b clientName = [%s]", authorized, clientName);
} catch (IOException e) {
log.trace("IOException during AuthorizeCallback handling", e);
throw log.mechServerSideAuthenticationFailed(SPNEGO_NAME, e).toHttpAuthenticationException();
} catch (UnsupportedCallbackException ignored) {
}
if (authorized) {
// If we fail the caller may still decide to try and continue authentication.
handleCallback(AuthenticationCompleteCallback.SUCCEEDED);
}
return authorized;
}
private void handleCallback(Callback callback) throws HttpAuthenticationException {
try {
MechanismUtil.handleCallbacks(SPNEGO_NAME, callbackHandler, callback);
} catch (AuthenticationMechanismException e) {
throw e.toHttpAuthenticationException();
} catch (UnsupportedCallbackException ignored) {
}
}
private static class SpnegoContext implements Serializable {
transient GSSContext gssContext;
transient KerberosTicket kerberosTicket;
}
}
| [ELY-1373] SPNEGO should not send base challenge on failed authorization | src/main/java/org/wildfly/security/http/impl/SpnegoAuthenticationMechanism.java | [ELY-1373] SPNEGO should not send base challenge on failed authorization | <ide><path>rc/main/java/org/wildfly/security/http/impl/SpnegoAuthenticationMechanism.java
<ide> return;
<ide> }
<ide>
<del> if (gssContext.isEstablished()) {
<add> if (gssContext.isEstablished()) { // no more tokens are needed from the peer
<ide> final GSSCredential gssCredential;
<ide>
<ide> try {
<ide> log.trace("Authorization of established GSSContext failed");
<ide> handleCallback(AuthenticationCompleteCallback.FAILED);
<ide> clearAttachments(storageScope);
<del> request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME),
<del> responseToken == null ? null : response -> sendChallenge(responseToken, response, FORBIDDEN));
<add> request.authenticationFailed(log.authenticationFailed(SPNEGO_NAME));
<ide> }
<ide> } else if (Arrays.equals(responseToken, NEG_STATE_REJECT)) {
<ide> // for IBM java - prevent sending UNAUTHORIZED for [negState = reject] token |
|
Java | bsd-2-clause | 73f172495a37700f68855595f2137c37e3783144 | 0 | sechel/jtem-halfedge,sechel/jtem-halfedge | /**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2006-2010, Technische Universität Berlin, jTEM
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.
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 de.jtem.halfedge.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Vertex;
/**
* Class providing static utility methods for half-edge data structures.
*
* @author Boris Springborn
*/
/**
* @author springb
*
*/
public final class HalfEdgeUtils {
// Don't instatiate.
private HalfEdgeUtils() {}
/**
* Test whether the half-edge data structure represents a valid surface.
*
* Checks whether the following conditions are satisfied.<br>
* <br>
* <b>1.</b> The edge list is not empty.<br>
* <br>
* For all edges {@code e} in the edge list: <br>
* <br>
* <b>2.</b> Neither {@link Edge#getNextEdge() e.getNextEdge()}, nor {@link Edge#getPreviousEdge() e.getPreviousEdge()},
* nor {@link Edge#getOppositeEdge() e.getOppositeEdge()} returns {@code null}.<br>
* <b>3.</b> {@link Edge#getTargetVertex() e.getTargetVertex()} does not return {@code null}.<br>
* <b>4.</b> {@link Edge#getLeftFace() e.getLeftFace()} and {@link Edge#getRightFace() e.getRightFace()} do not <i>both</i> return {@code null}. <br>
* <b>5.</b> {@link Edge#getLeftFace() getLeftFace()} returns the same face for {@code e} and {@code e.}{@link Edge#getNextEdge() getNextEdge()}.<br>
* <b>6.</b> {@link Edge#getTargetVertex() getTargetVertex()} returns the same vertex for {@code e} and
* {@code e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()}.<br>
* <br>
* For all faces {@code f} in the face list: <br>
* <br>
* <b>7.</b> There is at least one edge {@code e} in the edge list that has {@code f} as left face. That is, there are no isolated faces.<br>
* <b>8.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge()}, you can reach all edges with {@code f} as left face.<br>
* <br>
* For all vertices {@code v} in the vertex list:<br>
* <br>
* <b>9.</b> There is at least one edge {@code e} in the edge list that has {@code v} as target vertex. That is, there are no isolated vertices.<br>
* <b>10.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()},
* you can reach all edges with {@code v} as target vertex. <br>
* <b>11.</b> Among all edges {@code e} with {@code v} as target vertex, there is at most one for which {@link Edge#getLeftFace() e.getLeftFace()} returns {@code null}.
* <br>
* <br>
* Together with the invariants that are maintained by the classes in this package, this guarantees that the half-edge data structure encodes a cell
* decomposition of a surface.
*
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds) {
return isValidSurface(heds, false);
}
/**
* Test whether the half-edge data structure represents a valid surface and, optionally, give a reason if it fails the test.
* If the parameter is {@code false}, this method behaves exatly as {@link #isValidSurface(HalfEdgeDataStructure)}. If the parameter is {@code true},
* and the half-edge data structure fails to represent a valid surface, the method outputs a brief explanation to {@link System#err}.
* This feature is intended for debugging.
* @param printReasonForFailureToSystemErr {@code true} if you want output to {@link System#err}.
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds, boolean printReasonForFailureToSystemErr) {
// must have at least one edge
if (heds.getEdges().isEmpty()) {
if (printReasonForFailureToSystemErr) System.err.println("getEdges().isEmpty == true");
return false;
}
// check for null references
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getNextEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getNextEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getPreviousEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getPreviousEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getOppositeEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getOppositeEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getTargetVertex() returns null for edge " + e.getIndex());
return false;
}
// either left face or right face may be null but not both
if (e.getLeftFace() == null && e.getRightFace() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Left face and right face are null for edge " + e.getIndex());
return false;
}
}
// Check if edges in a cycle have same left face and edges in a cocycle have same target vertex
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getLeftFace() != e.getNextEdge().getLeftFace()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getLeftFace() != e.getNextEdge().getLeftFace() for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex() for edge " + e.getIndex());
return false;
}
}
// check if every face has a boundary edge
for (Face<?,?,?> f : heds.getFaces()) {
if (f.getBoundaryEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " has no boundary edge.");
return false;
}
}
// check if every vertex has an incoming edge
for (Vertex<?,?,?> v : heds.getVertices()) {
if (v.getIncomingEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " has no incoming edge.");
}
}
// check if each face corresponds to a unique edge cycle,
// each vertex corresponds to a unique edge cocycle,
// and that there is at most one edge in a vertex cocyle with left face == null
int ne = heds.numEdges();
int nf = heds.numFaces();
int nv = heds.numVertices();
assert (nv > 0 && ne > 0 && nf > 0);
boolean[] vertexMark = new boolean[nv];
boolean[] edgeMark = new boolean[ne];
boolean[] faceMark = new boolean[nf];
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Face<?,?,?> f = e.getLeftFace();
if (f != null) {
// has this edge's left face already occurred in another cycle?
if (faceMark[f.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " is contained in more than one edge cycle. (Found out while looking at " + e + ")");
return false;
}
// mark the left face
faceMark[f.getIndex()] = true;
}
// mark all edges in the edge cycle
edgeMark[e.getIndex()] = true;
for (Edge<?,?,?> e1 = e.getNextEdge(); e1 != e; e1 = e1.getNextEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
}
}
edgeMark = new boolean[ne]; // initialize to false again
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Vertex<?,?,?> v = e.getTargetVertex();
// has this edge's target vertex already occurred in another cycle?
if (vertexMark[v.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " is contained in more than one edge cocycle.");
return false;
}
// mark the left face
vertexMark[v.getIndex()] = true;
// mark all edges in the edge cocycle and check whether there's more than one with left face == null.
edgeMark[e.getIndex()] = true;
boolean leftFaceNull = e.getLeftFace() == null;
for (Edge<?,?,?> e1 = e.getNextEdge().getOppositeEdge(); e1 != e; e1 = e1.getNextEdge().getOppositeEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
if (e1.getLeftFace() == null) {
if (leftFaceNull) {
if (printReasonForFailureToSystemErr) System.err.println("There is more than one edge with target vertex " + v.getIndex() + " and left face null.");
return false;
}
leftFaceNull = true;
}
}
}
// passed all tests
return true;
}
/**
* Returns a list containing all vertices that are
* target vertices of the boundary of the given face
* @see {@link HalfEdgeUtils#boundaryEdges(Face)}
* @param <V>
* @param <E>
* @param <F>
* @param face the face
* @return
*/
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> List<V> boundaryVertices(F face) {
Collection<E> b = boundaryEdges(face);
LinkedList<V> vList = new LinkedList<V>();
for (E e : b) {
vList.add(e.getTargetVertex());
}
return vList;
}
/**
* Return a list of edges which belong to the boundary component
* of e0
* @param <E>
* @param <F>
* @param e0
* @return the list of boundary edges in the correct cyclic order
* starting with the given e
*/
static public <
E extends Edge<?,E,F>,
F extends Face<?,E,F>
> List<E> boundaryEdges(E e0) {
if (e0 == null) {
return Collections.emptyList();
}
if (e0.getLeftFace() != null) {
throw new IllegalArgumentException("No boundary edge given");
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (null != e.getLeftFace()) {
throw new RuntimeException("Edge " + e + " is not a boundary edge, " +
"although it is the next edge of an edge which is.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
} while (e != e0);
return result;
}
/**
* Return a list of the edges which have a given face as left face.
* <p>
* This method expects that if there is at least one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}, and that in the process
* {@code e} never becomes {@code null}.
* <p>
* The returned list contains the boundary edges in the correct cyclic order.
*
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return the list of boundary edges in the correct cyclic order
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> List<E> boundaryEdges(F face) {
final E e0 = face.getBoundaryEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (face != e.getLeftFace()) {
throw new RuntimeException("Edge " + e + " does not have face " + face + " as left face, " +
"although it is the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
} while (e != e0);
return result;
}
/**
* Returns a collection containing all edges of {@code heds} with left face equal to null.
* @param <E> the edge type
* @param heds the surface
* @return the collection of boundary edges
*/
static public <E extends Edge<?,E,?>> List<E> boundaryEdges(HalfEdgeDataStructure<?,E,?> heds) {
List<E>result = new ArrayList<E>();
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e);
}
}
return result;
}
/**
* Returns a collection containing all faces of {@code heds} with at least one boundary edge.
* @param <E> the edge type
* @param heds the surface
* @return the collection of boundary edges
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> Collection<F> boundaryFaces(HalfEdgeDataStructure<?,E,F> heds) {
Collection<F> result = new HashSet<F>();
List<E> boundaryedges = boundaryEdges(heds);
for (E e : boundaryedges)
result.add(e.getRightFace());
return result;
}
/**
* Returns a list containing lists for all boundary components
* of {@code hds} with left face equal to null.
* @param <E> the edge type
* @param hds the surface
* @return the collection of boundary components
* @see boundaryEdges
*/
static public <E extends Edge<?,E,?>> List<List<E>> boundaryComponents(HalfEdgeDataStructure<?,E,?> hds) {
List<List<E>> result = new ArrayList<List<E>>();
Set<E> b = new TreeSet<E>(boundaryEdges(hds));
while (!b.isEmpty()) {
List<E> c = new LinkedList<E>();
E first = b.iterator().next();
E e = first;
do {
assert b.contains(e);
c.add(e);
b.remove(e);
e = e.getNextEdge();
} while (e != first);
result.add(c);
}
return result;
}
/**
* Returns a collection of all boundary vertices of {@code surf}. Assumes that {@code surf} represents a valid surface.
* @param <V> the vertex type
* @param <E> the edge type
* @param surf
* @return collection of boundary vertices
*/
static public <V extends Vertex<V,E,?>, E extends Edge<V,E,?>> Collection<V> boundaryVertices(HalfEdgeDataStructure<V,E,?> surf) {
Collection<V> result = new ArrayList<V>();
for (E e : surf.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e.getTargetVertex());
}
}
return result;
}
/**
* Return a list of the edges which have a given vertex as target vertex.
* <p>
* This method expects that if there is one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}{@code .}{@link de.jtem.halfedge.Edge#getOppositeEdge() getOppositeEdge()},
* and that in the process {@code e} never becomes {@code null}.
* <p>
* The returned list contains the incoming edges in clockwise order.
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the vertex
* @return the list of incoming edges, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<E> incomingEdges(V vertex){
final E e0 = vertex.getIncomingEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (vertex != e.getTargetVertex()) {
throw new RuntimeException("Edge " + e + " does not have vertex " + vertex + " as target vertex, " +
"although it is the opposite of the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
e = e.getOppositeEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as opposite edge.");
}
} while (e != e0);
return result;
}
/**
* Return a list of the edges which have a given vertex as start vertex.
* @param vertex the vertex
* @return the list of outgoing edges, in clockwise order
* @see incomingEdges
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<E> outgoingEdges(V vertex){
List<E> incoming = incomingEdges(vertex);
List<E> result = new ArrayList<E>(incoming.size());
for (E e : incoming) {
result.add(e.getOppositeEdge());
}
return result;
}
/**
* Return a list of those vertices that are connected to a given {@code vertex} by an edge.
* <p>
* The {@code i}th element of in this list is simply<br>
* {@code vertex.}{@link #incomingEdges(Vertex) getIncomingEdges(vertex)}{@code .get(i).}{@link de.jtem.halfedge.Edge#getStartVertex() getStartVertex() }.<br>
* Thus, the preconditions of {@link #incomingEdges(Vertex)} apply.
* <p>
* The list contains the neighboring vertices in clockwise order, and it may contain the same vertex multiple times.
* (It may also contain {@code null}s.)
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the list of neighboring vertices.
* @return the list of neighbor vertices, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<V> neighboringVertices(V vertex) {
List<E> incoming = incomingEdges(vertex);
LinkedList<V> result = new LinkedList<V>();
for (E e : incoming) {
result.add(e.getStartVertex());
}
return result;
}
/**
* Return a list of faces that are incident with a given vertex.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* <p>
* The returned list contains the incident faces in clockwise order. It does not contain {@code null},
* even if the vertex is on the boundary.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param vertex the vertex
* @return the incident faces in clockwise order
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> List<F> facesIncidentWithVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
List<F> result = new LinkedList<F>();
for (E e : incoming) {
F f = e.getLeftFace();
if (f != null) {
result.add(f);
}
}
return result;
}
/**
* Test if a given vertex is on the boundary.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
*
* @param vertex
* @return {@code true} if there is an incoming edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getLeftFace() left face}, otherwise {@code false}.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> boolean isBoundaryVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
for (E e : incoming) {
if (e.getLeftFace() == null) {
return true;
}
}
return false;
}
/**
* Test if a given edge is on the boundary.
*
* @param e
* @return {@code true} if either e.getLeftFace() == null or e.getRightFace() == null.
*/
static public <E extends Edge<?, E, ?>> boolean isBoundaryEdge(E e) {
return e.getLeftFace() == null || e.getRightFace() == null;
}
/**
* Test if a given face is an inerior face (that is, not on the boundary).
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return {@code false} if there is a boundary edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getRightFace() right face}, otherwise {@code true}
*/
static public <F extends Face<?,E,F>, E extends Edge<?,E,F>> boolean isInteriorFace(F face){
for (E e : boundaryEdges(face))
if (e.getRightFace() == null) {
return false;
}
return true;
}
/**
* Test if a given edge is an interior edge (that is, not on the boundary).
* @param e the edge
* @return {@code e.getLeftFace() != null && e.getRightFace() != null}
*/
static public boolean isInteriorEdge(Edge<?,?,?> e){
return e.getLeftFace() != null && e.getRightFace() != null;
}
/**
* Insert a new face into an edge cycle with no left face.
* <p>
* An edge cycle is a cycle of edges obtained by repeatedly applying {@link de.jtem.halfedge.Edge#getNextEdge()}.
* This method expects that one does not encounter {@code null} when doing so, and that all edges in the cycle
* have {@code null} as left face.
*
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param edge an edge of the edge cycle
* @return the new face
* @throws RuntimeException if it is called with {@code null} as parameter, of if {@link de.jtem.halfedge.Edge#getNextEdge()}
* returns {@code null} for some edge in the edge cycle, or if {@link de.jtem.halfedge.Edge#getLeftFace} is not {@code null} for some
* edge in the cycle.
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F fillHole(E edge) throws RuntimeException {
// System.err.println("fillHole(" + edge + ")");
List<E> edgeList = new ArrayList<E>();
E e = edge;
do {
if (e == null) {
throw new RuntimeException("Method must not be called with null as parameter.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException(edge + " has a non-null left face. Null expected.");
}
edgeList.add(e);
e = e.getNextEdge();
} while (e != edge);
F f = edge.getHalfEdgeDataStructure().addNewFace();
// System.err.print("\tgluing " + f + " to ");
for (E ee : edgeList) {
// System.err.print(ee + " ");
ee.setLeftFace(f);
}
// System.err.println();
return f;
}
/**
* Fill all holes by adding faces.
* <p>
* Simply calls {@link #fillHole(Edge)} on edges with no left face until all edges have a left face.
* Hence, the preconditions described there apply.
*
* @param heds
*/
static public <V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>> void fillAllHoles(HalfEdgeDataStructure<V,E,F> heds) {
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
fillHole(e);
}
}
}
/**
* Add a new n-gon.
* <p>
* Increases the number of faces by 1, the number of edges by 2*n, and the number of vertices by n.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param n the number of vertices
* @return the new face
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F addNGon(HalfEdgeDataStructure<V,E,F> heds, int n) {
List<E> edges = heds.addNewEdges(n);
List<E> oppositeEdges = heds.addNewEdges(n);
List<V> vertices = heds.addNewVertices(n);
F face = heds.addNewFace();
for (int i = 0; i < n; i++) {
int iPlus1 = (i + 1) % n;
E eI = edges.get(i);
E eIPlus1 = edges.get(iPlus1);
E eOppI = oppositeEdges.get(i);
E eOppIPlus1 = oppositeEdges.get(iPlus1);
V vI = vertices.get(i);
eI.linkOppositeEdge(eOppI);
eI.linkNextEdge(eIPlus1);
eOppI.linkPreviousEdge(eOppIPlus1);
eI.setLeftFace(face);
eI.setTargetVertex(vI);
eOppIPlus1.setTargetVertex(vI);
}
return face;
}
/**
* Find an edge with given start and target vertices.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* @param <V> the vertex type
* @param <E> the edge type
* @param startVertex the start vertex
* @param targetVertex the target vertex
* @return an edge with those vertices as start and target vertices, or {@code null} if no such edge exists.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> E findEdgeBetweenVertices(V startVertex, V targetVertex) {
for (E e : incomingEdges(targetVertex)) {
if (startVertex == e.getStartVertex()) {
return e;
}
}
return null;
}
/**
* Find an edge with given left and right faces.
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param leftFace the left face
* @param rightFace the right face
* @return an edge with those faces as left and right face, or {@code null} if no such edge exists.
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> E findEdgeBetweenFaces(F leftFace, F rightFace) {
for (E e : boundaryEdges(leftFace)) {
if (rightFace == e.getRightFace()) {
return e;
}
}
return null;
}
/**
* Finds all edges with given left and right faces.
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param leftFace the left face
* @param rightFace the right face
* @return a list of edges with those faces as left and right face, or an empty list if no such edge exists.
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> List<E> findEdgesBetweenFaces(F leftFace, F rightFace) {
List<E> result = new LinkedList<E>();
for (E e : boundaryEdges(leftFace)) {
if (rightFace == e.getRightFace()) {
result.add(e);
}
}
return result;
}
/**
* Construct a new face by giving its vertices in cyclic order.
* <p>
* This method assumes:<br>
* <ul>
* <li>At least three non-null vertices are passed as parameters.</li>
* <li>They belong to the {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure} {@code heds}.</li>
* <li>Except for isolated vertices and missing faces, {@code heds} is a valid surface or empty. More precisely: If all vertices {@code v} with
* {@code v.}{@link de.jtem.halfedge.Vertex#getIncomingEdge() getIncomingEdge()}{@code == null}
* were removed from {@code heds}, and after executing {@link #fillAllHoles(HalfEdgeDataStructure) fillAllHoles(heds)}, {@code heds} would be empty or a
* {@linkplain de.jtem.halfedge.HalfEdgeDataStructure#isValidSurface() valid surface}.</li>
* <li>There are no loops or double edges in {@code heds}. More precisely: If {@code v0} and {@code v1} are vertices of {@code heds}
* (where {@code v0 == v1} is allowed) then there is at most one {@link de.jtem.halfedge.Edge Edge} with start vertex {@code v0}
* and target vertex {@code v1}.</li>
* <li>Adding a face with the given vertices will result in a {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure}
* without loops or double edges, which is again valid surface except for isolated vertices and missing faces. </li>
* </ul>
* <p>
* Failure of this method is not atomic: If it throws an exception, the half-edge data structure may be left in some intermediate state.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param v the vertices
* @return an edge with the new face as left face
* @throws RuntimeException in some cases when something goes wrong. Of course, this should not happen if the above preconditions are fulfilled.
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>>
E constructFaceByVertices(HalfEdgeDataStructure<V,E,F> heds, Vertex<?,?,?>... v) throws RuntimeException {
// System.err.print("constructFaceByVertices(");
// for (int i = 0; i < v.length; i ++) {
// System.err.print(v[i] + " ");
// }
// System.err.println(")");
if (heds == null) {
throw new RuntimeException("Null may not be passed as HalfEdgeDataStructure argument.");
}
if (v.length < 3) {
throw new RuntimeException("At least three vertices must be passed as arguments.");
}
// if (v[0] == null) {
// throw new RuntimeException("Null elements are not allowed as vertex arguments.");
// }
// HalfEdgeDataStructure<V,E,F> heds = v[0].getHalfEdgeDataStructure();
for (int i = 0; i < v.length; i++) {
if (v[i] == null) {
throw new RuntimeException("Null elements are not allowed in the vertex argument list.");
}
if (v[i].getHalfEdgeDataStructure() != heds) {
throw new RuntimeException(v[i] + " doesn't belong to " + heds + ".");
}
}
Class<V> vClass = heds.getVertexClass();
int numOldEdges = heds.numEdges();
List<E> edgeCycle = new ArrayList<E>();
for (int i = 0; i < v.length; i++) {
E e = findEdgeBetweenVertices(vClass.cast(v[i]), vClass.cast(v[(i+1) % v.length]));
if (e == null) {
// make a new pair of half-edges
// System.err.println("\tCreating edge pair from " + v[i] + " to " + v[(i+1) % v.length]);
e = heds.addNewEdge();
E eOpp = heds.addNewEdge();
e.linkOppositeEdge(eOpp);
} else {
if (e.getOppositeEdge() == null) {
throw new RuntimeException(e + " has no opposite edge.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException("There already is an edge from " + e.getStartVertex() + " to " + e.getTargetVertex()
+ " with " + e.getLeftFace() + " as left face.");
}
}
edgeCycle.add(e);
}
int n = edgeCycle.size();
for (int i0 = 0; i0 < n; i0++) {
int i1 = (i0 + 1) % n;
E e0 = edgeCycle.get(i0);
E e1 = edgeCycle.get(i1);
// V v0 = v[i0];
V v1 = vClass.cast(v[i1]);
if (e0.getIndex() >= numOldEdges) {
if (e1.getIndex() >= numOldEdges) {
// e0 and e1 are new
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
e1.getOppositeEdge().setTargetVertex(v1);
} else {
// e0 is new, e1 is old
E oldPrevEdge = e1.getPreviousEdge();
e0.linkNextEdge(e1);
oldPrevEdge.linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
}
} else {
if (e1.getIndex() >= numOldEdges) {
// e0 is old, e1 is new
E oldNextEdge = e0.getNextEdge();
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(oldNextEdge);
e1.getOppositeEdge().setTargetVertex(v1);
} // else e0 and e1 are old: nothing to do
}
}
fillHole(edgeCycle.get(0));
return edgeCycle.get(0);
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addTetrahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v1, v0, v3);
constructFaceByVertices(heds, v2, v1, v3);
constructFaceByVertices(heds, v0, v2, v3);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addCube(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3);
constructFaceByVertices(heds, v0, v4, v5, v1);
constructFaceByVertices(heds, v1, v5, v6, v2);
constructFaceByVertices(heds, v2, v6, v7, v3);
constructFaceByVertices(heds, v3, v7, v4, v0);
constructFaceByVertices(heds, v7, v6, v5, v4);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addOctahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v1);
constructFaceByVertices(heds, v2, v1, v5);
constructFaceByVertices(heds, v3, v2, v5);
constructFaceByVertices(heds, v4, v3, v5);
constructFaceByVertices(heds, v1, v4, v5);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addDodecahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
V v12 = heds.addNewVertex();
V v13 = heds.addNewVertex();
V v14 = heds.addNewVertex();
V v15 = heds.addNewVertex();
V v16 = heds.addNewVertex();
V v17 = heds.addNewVertex();
V v18 = heds.addNewVertex();
V v19 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3, v4);
constructFaceByVertices(heds, v0, v5, v10, v6, v1);
constructFaceByVertices(heds, v1, v6, v11, v7, v2);
constructFaceByVertices(heds, v2, v7, v12, v8, v3);
constructFaceByVertices(heds, v3, v8, v13, v9, v4);
constructFaceByVertices(heds, v4, v9, v14, v5, v0);
constructFaceByVertices(heds, v14, v15, v16, v10, v5);
constructFaceByVertices(heds, v10, v16, v17, v11, v6);
constructFaceByVertices(heds, v11, v17, v18, v12, v7);
constructFaceByVertices(heds, v12, v18, v19, v13, v8);
constructFaceByVertices(heds, v13, v19, v15, v14, v9);
constructFaceByVertices(heds, v19, v18, v17, v16, v15);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addIcosahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v5);
constructFaceByVertices(heds, v0, v5, v1);
constructFaceByVertices(heds, v2, v1, v7);
constructFaceByVertices(heds, v3, v2, v6);
constructFaceByVertices(heds, v4, v3, v10);
constructFaceByVertices(heds, v5, v4, v9);
constructFaceByVertices(heds, v1, v5, v8);
constructFaceByVertices(heds, v1, v8, v7);
constructFaceByVertices(heds, v2, v7, v6);
constructFaceByVertices(heds, v3, v6, v10);
constructFaceByVertices(heds, v4, v10, v9);
constructFaceByVertices(heds, v5, v9, v8);
constructFaceByVertices(heds, v7, v8, v11);
constructFaceByVertices(heds, v6, v7, v11);
constructFaceByVertices(heds, v10, v6, v11);
constructFaceByVertices(heds, v9, v10, v11);
constructFaceByVertices(heds, v8, v9, v11);
return eResult;
}
/**
* Calculates the genus of the 2-manifold represented
* by the given HalfedgeDataDtructure by evaluating
* X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces()
* r = number of boundary components
* g = (2 - X - r) / 2
* @param hds a 2-manifold
* @return g
*/
public static int getGenus(HalfEdgeDataStructure<?, ?, ?> hds) {
int r = boundaryComponents(hds).size();
int X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces();
return (2 - X - r) / 2;
}
/**
* Returns true if the neighborhood of this vertex is homeomorphic
* either to R2 or to a half-space
* @param v the vertex
* @return
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>
> boolean isManifoldVertex(V v) {
int bc = 0;
for (E e : incomingEdges(v)) {
if (e.getLeftFace() == null) {
bc++;
}
}
return bc <= 1;
}
/**
* Inserts the nodes of src into dst
* @param src
* @param dst
* @return The vertex offset of the new vertices in dst
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>,
HDSSRC extends HalfEdgeDataStructure<V, E, F>,
VV extends Vertex<VV,EE,FF>,
EE extends Edge<VV,EE,FF>,
FF extends Face<VV,EE,FF>,
HDSDST extends HalfEdgeDataStructure<VV, EE, FF>
> int copy(HDSSRC src, HDSDST dst) {
Set<E> srcEdges = new HashSet<E>(src.getEdges());
int vOffset = dst.numVertices();
int eOffset = dst.numEdges();
int fOffset = dst.numFaces();
dst.addNewVertices(src.numVertices());
dst.addNewEdges(src.numEdges());
dst.addNewFaces(src.numFaces());
for (E e : srcEdges) {
E eNext = e.getNextEdge();
E eOpp = e.getOppositeEdge();
F f = e.getLeftFace();
V v = e.getTargetVertex();
EE ee = dst.getEdge(eOffset + e.getIndex());
ee.setIsPositive(e.isPositive());
if (eNext != null) {
ee.linkNextEdge(dst.getEdge(eOffset + eNext.getIndex()));
}
if (eOpp != null) {
ee.linkOppositeEdge(dst.getEdge(eOffset + eOpp.getIndex()));
}
if (f != null) {
ee.setLeftFace(dst.getFace(fOffset + f.getIndex()));
}
if (v != null) {
ee.setTargetVertex(dst.getVertex(vOffset + v.getIndex()));
}
}
return vOffset;
}
}
| src/de/jtem/halfedge/util/HalfEdgeUtils.java | /**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2006-2010, Technische Universität Berlin, jTEM
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.
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 de.jtem.halfedge.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Vertex;
/**
* Class providing static utility methods for half-edge data structures.
*
* @author Boris Springborn
*/
/**
* @author springb
*
*/
public final class HalfEdgeUtils {
// Don't instatiate.
private HalfEdgeUtils() {}
/**
* Test whether the half-edge data structure represents a valid surface.
*
* Checks whether the following conditions are satisfied.<br>
* <br>
* <b>1.</b> The edge list is not empty.<br>
* <br>
* For all edges {@code e} in the edge list: <br>
* <br>
* <b>2.</b> Neither {@link Edge#getNextEdge() e.getNextEdge()}, nor {@link Edge#getPreviousEdge() e.getPreviousEdge()},
* nor {@link Edge#getOppositeEdge() e.getOppositeEdge()} returns {@code null}.<br>
* <b>3.</b> {@link Edge#getTargetVertex() e.getTargetVertex()} does not return {@code null}.<br>
* <b>4.</b> {@link Edge#getLeftFace() e.getLeftFace()} and {@link Edge#getRightFace() e.getRightFace()} do not <i>both</i> return {@code null}. <br>
* <b>5.</b> {@link Edge#getLeftFace() getLeftFace()} returns the same face for {@code e} and {@code e.}{@link Edge#getNextEdge() getNextEdge()}.<br>
* <b>6.</b> {@link Edge#getTargetVertex() getTargetVertex()} returns the same vertex for {@code e} and
* {@code e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()}.<br>
* <br>
* For all faces {@code f} in the face list: <br>
* <br>
* <b>7.</b> There is at least one edge {@code e} in the edge list that has {@code f} as left face. That is, there are no isolated faces.<br>
* <b>8.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge()}, you can reach all edges with {@code f} as left face.<br>
* <br>
* For all vertices {@code v} in the vertex list:<br>
* <br>
* <b>9.</b> There is at least one edge {@code e} in the edge list that has {@code v} as target vertex. That is, there are no isolated vertices.<br>
* <b>10.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()},
* you can reach all edges with {@code v} as target vertex. <br>
* <b>11.</b> Among all edges {@code e} with {@code v} as target vertex, there is at most one for which {@link Edge#getLeftFace() e.getLeftFace()} returns {@code null}.
* <br>
* <br>
* Together with the invariants that are maintained by the classes in this package, this guarantees that the half-edge data structure encodes a cell
* decomposition of a surface.
*
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds) {
return isValidSurface(heds, false);
}
/**
* Test whether the half-edge data structure represents a valid surface and, optionally, give a reason if it fails the test.
* If the parameter is {@code false}, this method behaves exatly as {@link #isValidSurface(HalfEdgeDataStructure)}. If the parameter is {@code true},
* and the half-edge data structure fails to represent a valid surface, the method outputs a brief explanation to {@link System#err}.
* This feature is intended for debugging.
* @param printReasonForFailureToSystemErr {@code true} if you want output to {@link System#err}.
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds, boolean printReasonForFailureToSystemErr) {
// must have at least one edge
if (heds.getEdges().isEmpty()) {
if (printReasonForFailureToSystemErr) System.err.println("getEdges().isEmpty == true");
return false;
}
// check for null references
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getNextEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getNextEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getPreviousEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getPreviousEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getOppositeEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getOppositeEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getTargetVertex() returns null for edge " + e.getIndex());
return false;
}
// either left face or right face may be null but not both
if (e.getLeftFace() == null && e.getRightFace() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Left face and right face are null for edge " + e.getIndex());
return false;
}
}
// Check if edges in a cycle have same left face and edges in a cocycle have same target vertex
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getLeftFace() != e.getNextEdge().getLeftFace()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getLeftFace() != e.getNextEdge().getLeftFace() for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex() for edge " + e.getIndex());
return false;
}
}
// check if every face has a boundary edge
for (Face<?,?,?> f : heds.getFaces()) {
if (f.getBoundaryEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " has no boundary edge.");
return false;
}
}
// check if every vertex has an incoming edge
for (Vertex<?,?,?> v : heds.getVertices()) {
if (v.getIncomingEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " has no incoming edge.");
}
}
// check if each face corresponds to a unique edge cycle,
// each vertex corresponds to a unique edge cocycle,
// and that there is at most one edge in a vertex cocyle with left face == null
int ne = heds.numEdges();
int nf = heds.numFaces();
int nv = heds.numVertices();
assert (nv > 0 && ne > 0 && nf > 0);
boolean[] vertexMark = new boolean[nv];
boolean[] edgeMark = new boolean[ne];
boolean[] faceMark = new boolean[nf];
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Face<?,?,?> f = e.getLeftFace();
if (f != null) {
// has this edge's left face already occurred in another cycle?
if (faceMark[f.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " is contained in more than one edge cycle. (Found out while looking at " + e + ")");
return false;
}
// mark the left face
faceMark[f.getIndex()] = true;
}
// mark all edges in the edge cycle
edgeMark[e.getIndex()] = true;
for (Edge<?,?,?> e1 = e.getNextEdge(); e1 != e; e1 = e1.getNextEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
}
}
edgeMark = new boolean[ne]; // initialize to false again
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Vertex<?,?,?> v = e.getTargetVertex();
// has this edge's target vertex already occurred in another cycle?
if (vertexMark[v.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " is contained in more than one edge cocycle.");
return false;
}
// mark the left face
vertexMark[v.getIndex()] = true;
// mark all edges in the edge cocycle and check whether there's more than one with left face == null.
edgeMark[e.getIndex()] = true;
boolean leftFaceNull = e.getLeftFace() == null;
for (Edge<?,?,?> e1 = e.getNextEdge().getOppositeEdge(); e1 != e; e1 = e1.getNextEdge().getOppositeEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
if (e1.getLeftFace() == null) {
if (leftFaceNull) {
if (printReasonForFailureToSystemErr) System.err.println("There is more than one edge with target vertex " + v.getIndex() + " and left face null.");
return false;
}
leftFaceNull = true;
}
}
}
// passed all tests
return true;
}
/**
* Returns a list containing all vertices that are
* target vertices of the boundary of the given face
* @see {@link HalfEdgeUtils#boundaryEdges(Face)}
* @param <V>
* @param <E>
* @param <F>
* @param face the face
* @return
*/
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> List<V> boundaryVertices(F face) {
Collection<E> b = boundaryEdges(face);
LinkedList<V> vList = new LinkedList<V>();
for (E e : b) {
vList.add(e.getTargetVertex());
}
return vList;
}
/**
* Return a list of edges which belong to the boundary component
* of e0
* @param <E>
* @param <F>
* @param e0
* @return the list of boundary edges in the correct cyclic order
* starting with the given e
*/
static public <
E extends Edge<?,E,F>,
F extends Face<?,E,F>
> List<E> boundaryEdges(E e0) {
if (e0 == null) {
return Collections.emptyList();
}
if (e0.getLeftFace() != null) {
throw new IllegalArgumentException("No boundary edge given");
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (null != e.getLeftFace()) {
throw new RuntimeException("Edge " + e + " is not a boundary edge, " +
"although it is the next edge of an edge which is.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
} while (e != e0);
return result;
}
/**
* Return a list of the edges which have a given face as left face.
* <p>
* This method expects that if there is at least one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}, and that in the process
* {@code e} never becomes {@code null}.
* <p>
* The returned list contains the boundary edges in the correct cyclic order.
*
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return the list of boundary edges in the correct cyclic order
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> List<E> boundaryEdges(F face) {
final E e0 = face.getBoundaryEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (face != e.getLeftFace()) {
throw new RuntimeException("Edge " + e + " does not have face " + face + " as left face, " +
"although it is the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
} while (e != e0);
return result;
}
/**
* Returns a collection containing all edges of {@code heds} with left face equal to null.
* @param <E> the edge type
* @param heds the surface
* @return the collection of boundary edges
*/
static public <E extends Edge<?,E,?>> List<E> boundaryEdges(HalfEdgeDataStructure<?,E,?> heds) {
List<E>result = new ArrayList<E>();
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e);
}
}
return result;
}
/**
* Returns a collection containing all faces of {@code heds} with at least one boundary edge.
* @param <E> the edge type
* @param heds the surface
* @return the collection of boundary edges
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> Collection<F> boundaryFaces(HalfEdgeDataStructure<?,E,F> heds) {
Collection<F> result = new HashSet<F>();
List<E> boundaryedges = boundaryEdges(heds);
for (E e : boundaryedges)
result.add(e.getRightFace());
return result;
}
/**
* Returns a list containing lists for all boundary components
* of {@code hds} with left face equal to null.
* @param <E> the edge type
* @param hds the surface
* @return the collection of boundary components
* @see boundaryEdges
*/
static public <E extends Edge<?,E,?>> List<List<E>> boundaryComponents(HalfEdgeDataStructure<?,E,?> hds) {
List<List<E>> result = new ArrayList<List<E>>();
Set<E> b = new TreeSet<E>(boundaryEdges(hds));
while (!b.isEmpty()) {
List<E> c = new LinkedList<E>();
E first = b.iterator().next();
E e = first;
do {
assert b.contains(e);
c.add(e);
b.remove(e);
e = e.getNextEdge();
} while (e != first);
result.add(c);
}
return result;
}
/**
* Returns a collection of all boundary vertices of {@code surf}. Assumes that {@code surf} represents a valid surface.
* @param <V> the vertex type
* @param <E> the edge type
* @param surf
* @return collection of boundary vertices
*/
static public <V extends Vertex<V,E,?>, E extends Edge<V,E,?>> Collection<V> boundaryVertices(HalfEdgeDataStructure<V,E,?> surf) {
Collection<V> result = new ArrayList<V>();
for (E e : surf.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e.getTargetVertex());
}
}
return result;
}
/**
* Return a list of the edges which have a given vertex as target vertex.
* <p>
* This method expects that if there is one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}{@code .}{@link de.jtem.halfedge.Edge#getOppositeEdge() getOppositeEdge()},
* and that in the process {@code e} never becomes {@code null}.
* <p>
* The returned list contains the incoming edges in clockwise order.
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the vertex
* @return the list of incoming edges, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<E> incomingEdges(V vertex){
final E e0 = vertex.getIncomingEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (vertex != e.getTargetVertex()) {
throw new RuntimeException("Edge " + e + " does not have vertex " + vertex + " as target vertex, " +
"although it is the opposite of the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
e = e.getOppositeEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as opposite edge.");
}
} while (e != e0);
return result;
}
/**
* Return a list of the edges which have a given vertex as start vertex.
* @param vertex the vertex
* @return the list of outgoing edges, in clockwise order
* @see incomingEdges
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<E> outgoingEdges(V vertex){
List<E> incoming = incomingEdges(vertex);
List<E> result = new ArrayList<E>(incoming.size());
for (E e : incoming) {
result.add(e.getOppositeEdge());
}
return result;
}
/**
* Return a list of those vertices that are connected to a given {@code vertex} by an edge.
* <p>
* The {@code i}th element of in this list is simply<br>
* {@code vertex.}{@link #incomingEdges(Vertex) getIncomingEdges(vertex)}{@code .get(i).}{@link de.jtem.halfedge.Edge#getStartVertex() getStartVertex() }.<br>
* Thus, the preconditions of {@link #incomingEdges(Vertex)} apply.
* <p>
* The list contains the neighboring vertices in clockwise order, and it may contain the same vertex multiple times.
* (It may also contain {@code null}s.)
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the list of neighboring vertices.
* @return the list of neighbor vertices, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<V> neighboringVertices(V vertex) {
List<E> incoming = incomingEdges(vertex);
LinkedList<V> result = new LinkedList<V>();
for (E e : incoming) {
result.add(e.getStartVertex());
}
return result;
}
/**
* Return a list of faces that are incident with a given vertex.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* <p>
* The returned list contains the incident faces in clockwise order. It does not contain {@code null},
* even if the vertex is on the boundary.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param vertex the vertex
* @return the incident faces in clockwise order
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> List<F> facesIncidentWithVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
List<F> result = new LinkedList<F>();
for (E e : incoming) {
F f = e.getLeftFace();
if (f != null) {
result.add(f);
}
}
return result;
}
/**
* Test if a given vertex is on the boundary.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
*
* @param vertex
* @return {@code true} if there is an incoming edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getLeftFace() left face}, otherwise {@code false}.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> boolean isBoundaryVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
for (E e : incoming) {
if (e.getLeftFace() == null) {
return true;
}
}
return false;
}
/**
* Test if a given edge is on the boundary.
*
* @param e
* @return {@code true} if either e.getLeftFace() == null or e.getRightFace() == null.
*/
static public <E extends Edge<?, E, ?>> boolean isBoundaryEdge(E e) {
return e.getLeftFace() == null || e.getRightFace() == null;
}
/**
* Test if a given face is an inerior face (that is, not on the boundary).
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return {@code false} if there is a boundary edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getRightFace() right face}, otherwise {@code true}
*/
static public <F extends Face<?,E,F>, E extends Edge<?,E,F>> boolean isInteriorFace(F face){
for (E e : boundaryEdges(face))
if (e.getRightFace() == null) {
return false;
}
return true;
}
/**
* Test if a given edge is an interior edge (that is, not on the boundary).
* @param e the edge
* @return {@code e.getLeftFace() != null && e.getRightFace() != null}
*/
static public boolean isInteriorEdge(Edge<?,?,?> e){
return e.getLeftFace() != null && e.getRightFace() != null;
}
/**
* Insert a new face into an edge cycle with no left face.
* <p>
* An edge cycle is a cycle of edges obtained by repeatedly applying {@link de.jtem.halfedge.Edge#getNextEdge()}.
* This method expects that one does not encounter {@code null} when doing so, and that all edges in the cycle
* have {@code null} as left face.
*
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param edge an edge of the edge cycle
* @return the new face
* @throws RuntimeException if it is called with {@code null} as parameter, of if {@link de.jtem.halfedge.Edge#getNextEdge()}
* returns {@code null} for some edge in the edge cycle, or if {@link de.jtem.halfedge.Edge#getLeftFace} is not {@code null} for some
* edge in the cycle.
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F fillHole(E edge) throws RuntimeException {
// System.err.println("fillHole(" + edge + ")");
List<E> edgeList = new ArrayList<E>();
E e = edge;
do {
if (e == null) {
throw new RuntimeException("Method must not be called with null as parameter.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException(edge + " has a non-null left face. Null expected.");
}
edgeList.add(e);
e = e.getNextEdge();
} while (e != edge);
F f = edge.getHalfEdgeDataStructure().addNewFace();
// System.err.print("\tgluing " + f + " to ");
for (E ee : edgeList) {
// System.err.print(ee + " ");
ee.setLeftFace(f);
}
// System.err.println();
return f;
}
/**
* Fill all holes by adding faces.
* <p>
* Simply calls {@link #fillHole(Edge)} on edges with no left face until all edges have a left face.
* Hence, the preconditions described there apply.
*
* @param heds
*/
static public <V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>> void fillAllHoles(HalfEdgeDataStructure<V,E,F> heds) {
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
fillHole(e);
}
}
}
/**
* Add a new n-gon.
* <p>
* Increases the number of faces by 1, the number of edges by 2*n, and the number of vertices by n.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param n the number of vertices
* @return the new face
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F addNGon(HalfEdgeDataStructure<V,E,F> heds, int n) {
List<E> edges = heds.addNewEdges(n);
List<E> oppositeEdges = heds.addNewEdges(n);
List<V> vertices = heds.addNewVertices(n);
F face = heds.addNewFace();
for (int i = 0; i < n; i++) {
int iPlus1 = (i + 1) % n;
E eI = edges.get(i);
E eIPlus1 = edges.get(iPlus1);
E eOppI = oppositeEdges.get(i);
E eOppIPlus1 = oppositeEdges.get(iPlus1);
V vI = vertices.get(i);
eI.linkOppositeEdge(eOppI);
eI.linkNextEdge(eIPlus1);
eOppI.linkPreviousEdge(eOppIPlus1);
eI.setLeftFace(face);
eI.setTargetVertex(vI);
eOppIPlus1.setTargetVertex(vI);
}
return face;
}
/**
* Find an edge with given start and target vertices.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* @param <V> the vertex type
* @param <E> the edge type
* @param startVertex the start vertex
* @param targetVertex the target vertex
* @return an edge with those vertices as start and target vertices, or {@code null} if no such edge exists.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> E findEdgeBetweenVertices(V startVertex, V targetVertex) {
for (E e : incomingEdges(targetVertex)) {
if (startVertex == e.getStartVertex()) {
return e;
}
}
return null;
}
/**
* Find an edge with given left and right faces.
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param leftFace the left face
* @param rightFace the right face
* @return an edge with those faces as left and right face, or {@code null} if no such edge exists.
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> E findEdgeBetweenFaces(F leftFace, F rightFace) {
for (E e : boundaryEdges(leftFace)) {
if (rightFace == e.getRightFace()) {
return e;
}
}
return null;
}
/**
* Construct a new face by giving its vertices in cyclic order.
* <p>
* This method assumes:<br>
* <ul>
* <li>At least three non-null vertices are passed as parameters.</li>
* <li>They belong to the {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure} {@code heds}.</li>
* <li>Except for isolated vertices and missing faces, {@code heds} is a valid surface or empty. More precisely: If all vertices {@code v} with
* {@code v.}{@link de.jtem.halfedge.Vertex#getIncomingEdge() getIncomingEdge()}{@code == null}
* were removed from {@code heds}, and after executing {@link #fillAllHoles(HalfEdgeDataStructure) fillAllHoles(heds)}, {@code heds} would be empty or a
* {@linkplain de.jtem.halfedge.HalfEdgeDataStructure#isValidSurface() valid surface}.</li>
* <li>There are no loops or double edges in {@code heds}. More precisely: If {@code v0} and {@code v1} are vertices of {@code heds}
* (where {@code v0 == v1} is allowed) then there is at most one {@link de.jtem.halfedge.Edge Edge} with start vertex {@code v0}
* and target vertex {@code v1}.</li>
* <li>Adding a face with the given vertices will result in a {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure}
* without loops or double edges, which is again valid surface except for isolated vertices and missing faces. </li>
* </ul>
* <p>
* Failure of this method is not atomic: If it throws an exception, the half-edge data structure may be left in some intermediate state.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param v the vertices
* @return an edge with the new face as left face
* @throws RuntimeException in some cases when something goes wrong. Of course, this should not happen if the above preconditions are fulfilled.
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>>
E constructFaceByVertices(HalfEdgeDataStructure<V,E,F> heds, Vertex<?,?,?>... v) throws RuntimeException {
// System.err.print("constructFaceByVertices(");
// for (int i = 0; i < v.length; i ++) {
// System.err.print(v[i] + " ");
// }
// System.err.println(")");
if (heds == null) {
throw new RuntimeException("Null may not be passed as HalfEdgeDataStructure argument.");
}
if (v.length < 3) {
throw new RuntimeException("At least three vertices must be passed as arguments.");
}
// if (v[0] == null) {
// throw new RuntimeException("Null elements are not allowed as vertex arguments.");
// }
// HalfEdgeDataStructure<V,E,F> heds = v[0].getHalfEdgeDataStructure();
for (int i = 0; i < v.length; i++) {
if (v[i] == null) {
throw new RuntimeException("Null elements are not allowed in the vertex argument list.");
}
if (v[i].getHalfEdgeDataStructure() != heds) {
throw new RuntimeException(v[i] + " doesn't belong to " + heds + ".");
}
}
Class<V> vClass = heds.getVertexClass();
int numOldEdges = heds.numEdges();
List<E> edgeCycle = new ArrayList<E>();
for (int i = 0; i < v.length; i++) {
E e = findEdgeBetweenVertices(vClass.cast(v[i]), vClass.cast(v[(i+1) % v.length]));
if (e == null) {
// make a new pair of half-edges
// System.err.println("\tCreating edge pair from " + v[i] + " to " + v[(i+1) % v.length]);
e = heds.addNewEdge();
E eOpp = heds.addNewEdge();
e.linkOppositeEdge(eOpp);
} else {
if (e.getOppositeEdge() == null) {
throw new RuntimeException(e + " has no opposite edge.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException("There already is an edge from " + e.getStartVertex() + " to " + e.getTargetVertex()
+ " with " + e.getLeftFace() + " as left face.");
}
}
edgeCycle.add(e);
}
int n = edgeCycle.size();
for (int i0 = 0; i0 < n; i0++) {
int i1 = (i0 + 1) % n;
E e0 = edgeCycle.get(i0);
E e1 = edgeCycle.get(i1);
// V v0 = v[i0];
V v1 = vClass.cast(v[i1]);
if (e0.getIndex() >= numOldEdges) {
if (e1.getIndex() >= numOldEdges) {
// e0 and e1 are new
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
e1.getOppositeEdge().setTargetVertex(v1);
} else {
// e0 is new, e1 is old
E oldPrevEdge = e1.getPreviousEdge();
e0.linkNextEdge(e1);
oldPrevEdge.linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
}
} else {
if (e1.getIndex() >= numOldEdges) {
// e0 is old, e1 is new
E oldNextEdge = e0.getNextEdge();
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(oldNextEdge);
e1.getOppositeEdge().setTargetVertex(v1);
} // else e0 and e1 are old: nothing to do
}
}
fillHole(edgeCycle.get(0));
return edgeCycle.get(0);
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addTetrahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v1, v0, v3);
constructFaceByVertices(heds, v2, v1, v3);
constructFaceByVertices(heds, v0, v2, v3);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addCube(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3);
constructFaceByVertices(heds, v0, v4, v5, v1);
constructFaceByVertices(heds, v1, v5, v6, v2);
constructFaceByVertices(heds, v2, v6, v7, v3);
constructFaceByVertices(heds, v3, v7, v4, v0);
constructFaceByVertices(heds, v7, v6, v5, v4);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addOctahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v1);
constructFaceByVertices(heds, v2, v1, v5);
constructFaceByVertices(heds, v3, v2, v5);
constructFaceByVertices(heds, v4, v3, v5);
constructFaceByVertices(heds, v1, v4, v5);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addDodecahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
V v12 = heds.addNewVertex();
V v13 = heds.addNewVertex();
V v14 = heds.addNewVertex();
V v15 = heds.addNewVertex();
V v16 = heds.addNewVertex();
V v17 = heds.addNewVertex();
V v18 = heds.addNewVertex();
V v19 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3, v4);
constructFaceByVertices(heds, v0, v5, v10, v6, v1);
constructFaceByVertices(heds, v1, v6, v11, v7, v2);
constructFaceByVertices(heds, v2, v7, v12, v8, v3);
constructFaceByVertices(heds, v3, v8, v13, v9, v4);
constructFaceByVertices(heds, v4, v9, v14, v5, v0);
constructFaceByVertices(heds, v14, v15, v16, v10, v5);
constructFaceByVertices(heds, v10, v16, v17, v11, v6);
constructFaceByVertices(heds, v11, v17, v18, v12, v7);
constructFaceByVertices(heds, v12, v18, v19, v13, v8);
constructFaceByVertices(heds, v13, v19, v15, v14, v9);
constructFaceByVertices(heds, v19, v18, v17, v16, v15);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addIcosahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v5);
constructFaceByVertices(heds, v0, v5, v1);
constructFaceByVertices(heds, v2, v1, v7);
constructFaceByVertices(heds, v3, v2, v6);
constructFaceByVertices(heds, v4, v3, v10);
constructFaceByVertices(heds, v5, v4, v9);
constructFaceByVertices(heds, v1, v5, v8);
constructFaceByVertices(heds, v1, v8, v7);
constructFaceByVertices(heds, v2, v7, v6);
constructFaceByVertices(heds, v3, v6, v10);
constructFaceByVertices(heds, v4, v10, v9);
constructFaceByVertices(heds, v5, v9, v8);
constructFaceByVertices(heds, v7, v8, v11);
constructFaceByVertices(heds, v6, v7, v11);
constructFaceByVertices(heds, v10, v6, v11);
constructFaceByVertices(heds, v9, v10, v11);
constructFaceByVertices(heds, v8, v9, v11);
return eResult;
}
/**
* Calculates the genus of the 2-manifold represented
* by the given HalfedgeDataDtructure by evaluating
* X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces()
* r = number of boundary components
* g = (2 - X - r) / 2
* @param hds a 2-manifold
* @return g
*/
public static int getGenus(HalfEdgeDataStructure<?, ?, ?> hds) {
int r = boundaryComponents(hds).size();
int X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces();
return (2 - X - r) / 2;
}
/**
* Returns true if the neighborhood of this vertex is homeomorphic
* either to R2 or to a half-space
* @param v the vertex
* @return
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>
> boolean isManifoldVertex(V v) {
int bc = 0;
for (E e : incomingEdges(v)) {
if (e.getLeftFace() == null) {
bc++;
}
}
return bc <= 1;
}
/**
* Inserts the nodes of src into dst
* @param src
* @param dst
* @return The vertex offset of the new vertices in dst
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>,
HDSSRC extends HalfEdgeDataStructure<V, E, F>,
VV extends Vertex<VV,EE,FF>,
EE extends Edge<VV,EE,FF>,
FF extends Face<VV,EE,FF>,
HDSDST extends HalfEdgeDataStructure<VV, EE, FF>
> int copy(HDSSRC src, HDSDST dst) {
Set<E> srcEdges = new HashSet<E>(src.getEdges());
int vOffset = dst.numVertices();
int eOffset = dst.numEdges();
int fOffset = dst.numFaces();
dst.addNewVertices(src.numVertices());
dst.addNewEdges(src.numEdges());
dst.addNewFaces(src.numFaces());
for (E e : srcEdges) {
E eNext = e.getNextEdge();
E eOpp = e.getOppositeEdge();
F f = e.getLeftFace();
V v = e.getTargetVertex();
EE ee = dst.getEdge(eOffset + e.getIndex());
ee.setIsPositive(e.isPositive());
if (eNext != null) {
ee.linkNextEdge(dst.getEdge(eOffset + eNext.getIndex()));
}
if (eOpp != null) {
ee.linkOppositeEdge(dst.getEdge(eOffset + eOpp.getIndex()));
}
if (f != null) {
ee.setLeftFace(dst.getFace(fOffset + f.getIndex()));
}
if (v != null) {
ee.setTargetVertex(dst.getVertex(vOffset + v.getIndex()));
}
}
return vOffset;
}
}
| add findEdgesBetweenFaces method to the utilities
git-svn-id: 03edb61ddfd7a116a155cc4ee4a25ffdd5f61cac@1660 f5b180c5-49ee-4939-b20e-b6ed35f0f7b7
| src/de/jtem/halfedge/util/HalfEdgeUtils.java | add findEdgesBetweenFaces method to the utilities | <ide><path>rc/de/jtem/halfedge/util/HalfEdgeUtils.java
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Finds all edges with given left and right faces.
<add> * <p>
<add> * Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
<add> * @param <E> the edge type
<add> * @param <F> the face type
<add> * @param leftFace the left face
<add> * @param rightFace the right face
<add> * @return a list of edges with those faces as left and right face, or an empty list if no such edge exists.
<add> */
<add> static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> List<E> findEdgesBetweenFaces(F leftFace, F rightFace) {
<add> List<E> result = new LinkedList<E>();
<add> for (E e : boundaryEdges(leftFace)) {
<add> if (rightFace == e.getRightFace()) {
<add> result.add(e);
<add> }
<add> }
<add> return result;
<add> }
<add>
<add>
<ide> /**
<ide> * Construct a new face by giving its vertices in cyclic order.
<ide> * <p> |
|
Java | agpl-3.0 | 6f0a02c0166715226146720318014906506e4127 | 0 | sfloresm/rstudio,JanMarvin/rstudio,edrogers/rstudio,pssguy/rstudio,vbelakov/rstudio,suribes/rstudio,githubfun/rstudio,JanMarvin/rstudio,thklaus/rstudio,suribes/rstudio,brsimioni/rstudio,JanMarvin/rstudio,vbelakov/rstudio,jar1karp/rstudio,jrnold/rstudio,jar1karp/rstudio,jzhu8803/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,maligulzar/Rstudio-instrumented,piersharding/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,more1/rstudio,suribes/rstudio,tbarrongh/rstudio,jar1karp/rstudio,JanMarvin/rstudio,edrogers/rstudio,piersharding/rstudio,more1/rstudio,jzhu8803/rstudio,sfloresm/rstudio,sfloresm/rstudio,vbelakov/rstudio,more1/rstudio,jar1karp/rstudio,edrogers/rstudio,jzhu8803/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,john-r-mcpherson/rstudio,maligulzar/Rstudio-instrumented,thklaus/rstudio,vbelakov/rstudio,suribes/rstudio,edrogers/rstudio,nvoron23/rstudio,pssguy/rstudio,brsimioni/rstudio,JanMarvin/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,jzhu8803/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,piersharding/rstudio,thklaus/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,thklaus/rstudio,john-r-mcpherson/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,nvoron23/rstudio,john-r-mcpherson/rstudio,jar1karp/rstudio,pssguy/rstudio,more1/rstudio,nvoron23/rstudio,vbelakov/rstudio,suribes/rstudio,githubfun/rstudio,pssguy/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jrnold/rstudio,thklaus/rstudio,vbelakov/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,githubfun/rstudio,pssguy/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,tbarrongh/rstudio,vbelakov/rstudio,brsimioni/rstudio,jzhu8803/rstudio,suribes/rstudio,edrogers/rstudio,jrnold/rstudio,tbarrongh/rstudio,vbelakov/rstudio,piersharding/rstudio,pssguy/rstudio,thklaus/rstudio,more1/rstudio,suribes/rstudio,jar1karp/rstudio,piersharding/rstudio,more1/rstudio,nvoron23/rstudio,tbarrongh/rstudio,more1/rstudio,piersharding/rstudio,tbarrongh/rstudio,piersharding/rstudio,jar1karp/rstudio,brsimioni/rstudio,edrogers/rstudio,brsimioni/rstudio,nvoron23/rstudio,githubfun/rstudio,jrnold/rstudio,piersharding/rstudio,githubfun/rstudio,sfloresm/rstudio,jar1karp/rstudio,jzhu8803/rstudio,JanMarvin/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,nvoron23/rstudio,john-r-mcpherson/rstudio,githubfun/rstudio,jzhu8803/rstudio,more1/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,brsimioni/rstudio,pssguy/rstudio,sfloresm/rstudio,edrogers/rstudio,thklaus/rstudio,jzhu8803/rstudio,nvoron23/rstudio,suribes/rstudio,jrnold/rstudio,jrnold/rstudio,jrnold/rstudio | /*
* Packages.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.packages;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.widget.MessageDialog;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.OperationWithInput;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.application.events.DeferredInitCompletedEvent;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.application.events.SuspendAndRestartEvent;
import org.rstudio.studio.client.application.model.SuspendOptions;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.mirrors.DefaultCRANMirror;
import org.rstudio.studio.client.packrat.Packrat;
import org.rstudio.studio.client.packrat.model.PackratContext;
import org.rstudio.studio.client.server.ServerDataSource;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.WorkbenchView;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ClientState;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue;
import org.rstudio.studio.client.workbench.views.BasePresenter;
import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptEvent;
import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptHandler;
import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent;
import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent;
import org.rstudio.studio.client.workbench.views.packages.events.InstalledPackagesChangedEvent;
import org.rstudio.studio.client.workbench.views.packages.events.InstalledPackagesChangedHandler;
import org.rstudio.studio.client.workbench.views.packages.events.LoadedPackageUpdatesEvent;
import org.rstudio.studio.client.workbench.views.packages.events.PackageStatusChangedEvent;
import org.rstudio.studio.client.workbench.views.packages.events.PackageStatusChangedHandler;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInfo;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallContext;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallOptions;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallRequest;
import org.rstudio.studio.client.workbench.views.packages.model.PackageLibraryUtils;
import org.rstudio.studio.client.workbench.views.packages.model.PackageState;
import org.rstudio.studio.client.workbench.views.packages.model.PackageStatus;
import org.rstudio.studio.client.workbench.views.packages.model.PackageUpdate;
import org.rstudio.studio.client.workbench.views.packages.model.PackagesServerOperations;
import org.rstudio.studio.client.workbench.views.packages.ui.CheckForUpdatesDialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
public class Packages
extends BasePresenter
implements InstalledPackagesChangedHandler,
PackageStatusChangedHandler,
DeferredInitCompletedEvent.Handler,
PackagesDisplayObserver
{
public interface Binder extends CommandBinder<Commands, Packages> {}
public interface Display extends WorkbenchView
{
void setPackageState(PackratContext packratContext,
List<PackageInfo> packagesDS);
void installPackage(PackageInstallContext installContext,
PackageInstallOptions defaultInstallOptions,
PackagesServerOperations server,
GlobalDisplay globalDisplay,
OperationWithInput<PackageInstallRequest> operation);
void setPackageStatus(PackageStatus status);
void setObserver(PackagesDisplayObserver observer) ;
void setProgress(boolean showProgress);
}
@Inject
public Packages(Display view,
final EventBus events,
PackagesServerOperations server,
GlobalDisplay globalDisplay,
Session session,
Binder binder,
Commands commands,
WorkbenchContext workbenchContext,
DefaultCRANMirror defaultCRANMirror)
{
super(view);
view_ = view;
server_ = server;
globalDisplay_ = globalDisplay ;
view_.setObserver(this) ;
events_ = events ;
defaultCRANMirror_ = defaultCRANMirror;
workbenchContext_ = workbenchContext;
session_ = session;
binder.bind(commands, this);
packrat_ = new Packrat(view);
events.addHandler(InstalledPackagesChangedEvent.TYPE, this);
events.addHandler(PackageStatusChangedEvent.TYPE, this);
// make the install options persistent
new JSObjectStateValue("packages-pane", "installOptions", ClientState.PROJECT_PERSISTENT,
session.getSessionInfo().getClientState(), false)
{
@Override
protected void onInit(JsObject value)
{
if (value != null)
installOptions_ = value.cast();
lastKnownState_ = installOptions_;
}
@Override
protected JsObject getValue()
{
return installOptions_.cast();
}
@Override
protected boolean hasChanged()
{
if (!PackageInstallOptions.areEqual(lastKnownState_, installOptions_))
{
lastKnownState_ = installOptions_;
return true;
}
return false;
}
private PackageInstallOptions lastKnownState_;
};
updatePackageState();
// after 2 seconds also add the DeferredInitCompleted handler
// (we wait because if we don't then on first load in a new
// session where the packages tab is showing updatePackageState
// will be called twice)
new Timer() {
@Override
public void run()
{
events.addHandler(DeferredInitCompletedEvent.TYPE, Packages.this);
}
}.schedule(2000);
}
void onInstallPackage()
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
if (installContext.isDefaultLibraryWriteable())
{
continueInstallPackage(installContext);
}
else
{
globalDisplay_.showYesNoMessage(MessageDialog.QUESTION,
"Create Package Library",
"Would you like to create a personal library '" +
installContext.getDefaultUserLibraryPath() + "' " +
"to install packages into?",
false,
new Operation() // Yes operation
{
@Override
public void execute()
{
ProgressIndicator indicator =
globalDisplay_.getProgressIndicator(
"Error Creating Library");
server_.initDefaultUserLibrary(
new VoidServerRequestCallback(indicator) {
@Override
protected void onSuccess()
{
// call this function back recursively
// so we can retrieve the updated
// PackageInstallContext from the server
onInstallPackage();
}
});
}
},
new Operation() // No operation
{
@Override
public void execute()
{
globalDisplay_.showMessage(
MessageDialog.WARNING,
"Install Packages",
"Unable to install packages (default library '" +
installContext.getDefaultLibraryPath() + "' is " +
"not writeable)");
}
},
true);
}
}
});
}
private void continueInstallPackage(
final PackageInstallContext installContext)
{
// if CRAN needs to be configured then do it
if (!installContext.isCRANMirrorConfigured())
{
defaultCRANMirror_.configure(new Command() {
public void execute()
{
doInstallPackage(installContext);
}
});
}
else
{
doInstallPackage(installContext);
}
}
private void doInstallPackage(final PackageInstallContext installContext)
{
// if install options have not yet initialized the default library
// path then set it now from the context
if (StringUtil.isNullOrEmpty(installOptions_.getLibraryPath()))
{
installOptions_ = PackageInstallOptions.create(
installOptions_.getInstallFromRepository(),
installContext.getDefaultLibraryPath(),
installOptions_.getInstallDependencies());
}
view_.installPackage(
installContext,
installOptions_,
server_,
globalDisplay_,
new OperationWithInput<PackageInstallRequest>()
{
public void execute(PackageInstallRequest request)
{
installOptions_ = request.getOptions();
boolean usingDefaultLibrary =
request.getOptions().getLibraryPath().equals(
installContext.getDefaultLibraryPath());
StringBuilder command = new StringBuilder();
command.append("install.packages(");
List<String> packages = request.getPackages();
if (packages != null)
{
if (packages.size() > 1)
command.append("c(");
for (int i=0; i<packages.size(); i++)
{
if (i > 0)
command.append(", ");
command.append("\"");
command.append(packages.get(i));
command.append("\"");
}
if (packages.size() > 1)
command.append(")");
// dependencies
if (!request.getOptions().getInstallDependencies())
command.append(", dependencies = FALSE");
}
// must be a local package
else
{
// get path
FileSystemItem localPackage = request.getLocalPackage();
// convert to string
String path = localPackage.getPath();
// append command
command.append("\"" + path + "\", repos = NULL");
// append type = source if needed
if (path.endsWith(".tar.gz"))
command.append(", type = \"source\"");
}
if (!usingDefaultLibrary)
{
command.append(", lib=\"");
command.append(request.getOptions().getLibraryPath());
command.append("\"");
}
command.append(")");
String cmd = command.toString();
executeWithLoadedPackageCheck(new InstallCommand(packages, cmd));
}
});
}
void onUpdatePackages()
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
// if there are no writeable library paths then we just
// short circuit to all packages are up to date message
if (installContext.getWriteableLibraryPaths().length() == 0)
{
globalDisplay_.showMessage(MessageDialog.INFO,
"Check for Updates",
"All packages are up to date.");
}
// if CRAN needs to be configured then do it
else if (!installContext.isCRANMirrorConfigured())
{
defaultCRANMirror_.configure(new Command() {
public void execute()
{
doUpdatePackages(installContext);
}
});
}
// otherwise we are good to go!
else
{
doUpdatePackages(installContext);
}
}
});
}
private void doUpdatePackages(final PackageInstallContext installContext)
{
new CheckForUpdatesDialog(
globalDisplay_,
new ServerDataSource<JsArray<PackageUpdate>>() {
public void requestData(
ServerRequestCallback<JsArray<PackageUpdate>> requestCallback)
{
server_.checkForPackageUpdates(requestCallback);
}
},
new OperationWithInput<ArrayList<PackageUpdate>>() {
@Override
public void execute(ArrayList<PackageUpdate> updates)
{
InstallCommand cmd = buildUpdatePackagesCommand(updates,
installContext);
executeWithLoadedPackageCheck(cmd);
}
},
new Operation() {
@Override
public void execute()
{
// cancel emits an empty console input line to clear
// the busy indicator
events_.fireEvent(new SendToConsoleEvent("", true));
}
}).showModal();
}
private InstallCommand buildUpdatePackagesCommand(
ArrayList<PackageUpdate> updates,
final PackageInstallContext installContext)
{
// split the updates into their respective target libraries
List<String> packages = new ArrayList<String>();
LinkedHashMap<String, ArrayList<PackageUpdate>> updatesByLibPath =
new LinkedHashMap<String, ArrayList<PackageUpdate>>();
for (PackageUpdate update : updates)
{
// auto-create target list if necessary
String libPath = update.getLibPath();
if (!updatesByLibPath.containsKey(libPath))
updatesByLibPath.put(libPath, new ArrayList<PackageUpdate>());
// insert into list
updatesByLibPath.get(libPath).add(update);
// track global list of packages
packages.add(update.getPackageName());
}
// generate an install packages command for each targeted library
StringBuilder command = new StringBuilder();
for (String libPath : updatesByLibPath.keySet())
{
if (command.length() > 0)
command.append("\n");
ArrayList<PackageUpdate> libPathUpdates = updatesByLibPath.get(libPath);
command.append("install.packages(");
if (libPathUpdates.size() > 1)
command.append("c(");
for (int i=0; i<libPathUpdates.size(); i++)
{
PackageUpdate update = libPathUpdates.get(i);
if (i > 0)
command.append(", ");
command.append("\"");
command.append(update.getPackageName());
command.append("\"");
}
if (libPathUpdates.size() > 1)
command.append(")");
if (!libPath.equals(installContext.getDefaultLibraryPath()))
{
command.append(", lib=\"");
command.append(libPath);
command.append("\"");
}
command.append(")");
}
return new InstallCommand(packages, command.toString());
}
@Handler
public void onRefreshPackages()
{
updatePackageState();
}
public void removePackage(final PackageInfo packageInfo)
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
final boolean usingDefaultLibrary = packageInfo.getLibrary().equals(
installContext.getDefaultLibraryPath());
StringBuilder message = new StringBuilder();
message.append("Are you sure you wish to permanently uninstall the '");
message.append(packageInfo.getName() + "' package");
if (!usingDefaultLibrary)
{
message.append(" from library '");
message.append(packageInfo.getLibrary());
message.append("'");
}
message.append("? This action cannot be undone.");
globalDisplay_.showYesNoMessage(
MessageDialog.WARNING,
"Uninstall Package ",
message.toString(),
new Operation()
{
@Override
public void execute()
{
StringBuilder command = new StringBuilder();
command.append("remove.packages(\"");
command.append(packageInfo.getName());
command.append("\"");
if (!usingDefaultLibrary)
{
command.append(", lib=\"");
command.append(packageInfo.getLibrary());
command.append("\"");
}
command.append(")");
String cmd = command.toString();
events_.fireEvent(new SendToConsoleEvent(cmd, true));
}
},
true);
}
});
}
@Override
public void updatePackageState()
{
view_.setProgress(true);
server_.getPackageState(new PackageStateUpdater());
}
public void loadPackage(final String packageName, final String libName)
{
// check status to make sure the package was unloaded
checkPackageStatusOnNextConsolePrompt(packageName, libName);
// send the command
StringBuilder command = new StringBuilder();
command.append("library(\"");
command.append(packageName);
command.append("\"");
command.append(", lib.loc=\"");
command.append(libName);
command.append("\"");
command.append(")");
events_.fireEvent(new SendToConsoleEvent(command.toString(), true));
}
public void unloadPackage(String packageName, String libName)
{
// check status to make sure the package was unloaded
checkPackageStatusOnNextConsolePrompt(packageName, libName);
StringBuilder command = new StringBuilder();
command.append("detach(\"package:");
command.append(packageName);
command.append("\", unload=TRUE)");
events_.fireEvent(new SendToConsoleEvent(command.toString(), true));
}
public void showHelp(PackageInfo packageInfo)
{
events_.fireEvent(new ShowHelpEvent(packageInfo.getUrl())) ;
}
public void onInstalledPackagesChanged(InstalledPackagesChangedEvent event)
{
updatePackageState() ;
}
@Override
public void onDeferredInitCompleted(DeferredInitCompletedEvent event)
{
updatePackageState();
}
public void onPackageFilterChanged(String filter)
{
packageFilter_ = filter.toLowerCase();
setViewPackageList();
}
public void onPackageStatusChanged(PackageStatusChangedEvent event)
{
PackageStatus status = event.getPackageStatus();
view_.setPackageStatus(status);
// also update the list of allPackages_
for (int i = 0; i<allPackages_.size(); i++)
{
PackageInfo packageInfo = allPackages_.get(i);
if (packageInfo.getName().equals(status.getName()) &&
packageInfo.getLibrary().equals(status.getLib()))
{
allPackages_.set(i, status.isLoaded() ? packageInfo.asLoaded() :
packageInfo.asUnloaded());
}
}
}
private void setViewPackageList()
{
ArrayList<PackageInfo> packages = null;
// apply filter (if any)
if (packageFilter_.length() > 0)
{
packages = new ArrayList<PackageInfo>();
// first do prefix search
for (PackageInfo pkgInfo : allPackages_)
{
if (pkgInfo.getName().toLowerCase().startsWith(packageFilter_))
packages.add(pkgInfo);
}
// then do contains search on name & desc
for (PackageInfo pkgInfo : allPackages_)
{
if (pkgInfo.getName().toLowerCase().contains(packageFilter_) ||
pkgInfo.getDesc().toLowerCase().contains(packageFilter_))
{
if (!packages.contains(pkgInfo))
packages.add(pkgInfo);
}
}
}
else
{
packages = allPackages_;
}
view_.setPackageState(packratContext_, packages);
}
private void checkPackageStatusOnNextConsolePrompt(
final String packageName,
final String libName)
{
// remove any existing handler
removeConsolePromptHandler();
consolePromptHandlerReg_ = events_.addHandler(ConsolePromptEvent.TYPE,
new ConsolePromptHandler() {
@Override
public void onConsolePrompt(ConsolePromptEvent event)
{
// remove handler so it is only called once
removeConsolePromptHandler();
// check status and set it
server_.isPackageLoaded(
packageName,
libName,
new ServerRequestCallback<Boolean>() {
@Override
public void onResponseReceived(Boolean status)
{
PackageStatus pkgStatus = PackageStatus.create(packageName,
libName,
status);
view_.setPackageStatus(pkgStatus);
}
@Override
public void onError(ServerError error)
{
// ignore errors
}
});
}
});
}
private void removeConsolePromptHandler()
{
if (consolePromptHandlerReg_ != null)
{
consolePromptHandlerReg_.removeHandler();
consolePromptHandlerReg_ = null;
}
}
private void withPackageInstallContext(
final OperationWithInput<PackageInstallContext> operation)
{
final ProgressIndicator indicator =
globalDisplay_.getProgressIndicator("Error");
indicator.onProgress("Retrieving package installation context...");
server_.getPackageInstallContext(
new SimpleRequestCallback<PackageInstallContext>() {
@Override
public void onResponseReceived(PackageInstallContext context)
{
indicator.onCompleted();
operation.execute(context);
}
@Override
public void onError(ServerError error)
{
indicator.onError(error.getUserMessage());
}
});
}
public void onLoadedPackageUpdates(LoadedPackageUpdatesEvent event)
{
restartForInstallWithConfirmation(event.getInstallCmd());
}
private class InstallCommand
{
public InstallCommand(List<String> packages, String cmd)
{
this.packages = packages;
this.cmd = cmd;
}
public final List<String> packages;
public final String cmd;
}
private void executeWithLoadedPackageCheck(final InstallCommand command)
{
// check if we are potentially going to be overwriting an
// already installed package. if so then prompt for restart
if ((command.packages != null))
{
server_.loadedPackageUpdatesRequired(
command.packages,
new ServerRequestCallback<Boolean>() {
@Override
public void onResponseReceived(Boolean required)
{
if (required)
{
restartForInstallWithConfirmation(command.cmd);
}
else
{
executePkgCommand(command.cmd);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
executePkgCommand(command.cmd);
}
});
}
else
{
executePkgCommand(command.cmd);
}
}
private void executePkgCommand(String cmd)
{
events_.fireEvent(new SendToConsoleEvent(cmd, true));
}
private void restartForInstallWithConfirmation(final String installCmd)
{
String msg = "One or more of the packages that will be updated by this " +
"installation are currently loaded. Restarting R prior " +
"to updating these packages is strongly recommended.\n\n" +
"RStudio can restart R and then automatically continue " +
"the installation after restarting (all work and " +
"data will be preserved during the restart).\n\n" +
"Do you want to restart R prior to installing?";
final boolean haveInstallCmd = installCmd.startsWith("install.packages");
globalDisplay_.showYesNoMessage(
MessageDialog.WARNING,
"Updating Loaded Packages",
msg,
true,
new Operation() { public void execute()
{
events_.fireEvent(new SuspendAndRestartEvent(
SuspendOptions.createSaveAll(true), installCmd));
}},
new Operation() { public void execute()
{
server_.ignoreNextLoadedPackageCheck(
new VoidServerRequestCallback() {
@Override
public void onSuccess()
{
if (haveInstallCmd)
executePkgCommand(installCmd);
}
});
}},
true);
}
private class PackageStateUpdater extends SimpleRequestCallback<PackageState>
{
public PackageStateUpdater()
{
super("Error Listing Packages");
}
@Override
public void onError(ServerError error)
{
// don't show errors during restart
if (!workbenchContext_.isRestartInProgress())
super.onError(error);
view_.setProgress(false);
}
@Override
public void onResponseReceived(PackageState response)
{
// sort the packages
allPackages_ = new ArrayList<PackageInfo>();
JsArray<PackageInfo> serverPackages = response.getPackageList();
for (int i = 0; i < serverPackages.length(); i++)
allPackages_.add(serverPackages.get(i));
Collections.sort(allPackages_, new Comparator<PackageInfo>() {
public int compare(PackageInfo o1, PackageInfo o2)
{
// sort first by library, then by name
int library =
PackageLibraryUtils.typeOfLibrary(
session_, o1.getLibrary()).compareTo(
PackageLibraryUtils.typeOfLibrary(
session_, o2.getLibrary()));
return library == 0 ?
o1.getName().compareToIgnoreCase(o2.getName()) :
library;
}
});
packratContext_ = response.getPackratContext();
view_.setProgress(false);
setViewPackageList();
}
};
private final Display view_;
private final PackagesServerOperations server_;
private ArrayList<PackageInfo> allPackages_ = new ArrayList<PackageInfo>();
private PackratContext packratContext_;
private String packageFilter_ = new String();
private HandlerRegistration consolePromptHandlerReg_ = null;
private final EventBus events_ ;
private final GlobalDisplay globalDisplay_ ;
private final WorkbenchContext workbenchContext_;
private final DefaultCRANMirror defaultCRANMirror_;
private final Session session_;
@SuppressWarnings("unused")
private final Packrat packrat_;
private PackageInstallOptions installOptions_ =
PackageInstallOptions.create(true, "", true);
}
| src/gwt/src/org/rstudio/studio/client/workbench/views/packages/Packages.java | /*
* Packages.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.packages;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.inject.Inject;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.widget.MessageDialog;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.OperationWithInput;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.application.events.DeferredInitCompletedEvent;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.application.events.SuspendAndRestartEvent;
import org.rstudio.studio.client.application.model.SuspendOptions;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.mirrors.DefaultCRANMirror;
import org.rstudio.studio.client.packrat.Packrat;
import org.rstudio.studio.client.packrat.model.PackratContext;
import org.rstudio.studio.client.server.ServerDataSource;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.WorkbenchView;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ClientState;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue;
import org.rstudio.studio.client.workbench.views.BasePresenter;
import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptEvent;
import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptHandler;
import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent;
import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent;
import org.rstudio.studio.client.workbench.views.packages.events.InstalledPackagesChangedEvent;
import org.rstudio.studio.client.workbench.views.packages.events.InstalledPackagesChangedHandler;
import org.rstudio.studio.client.workbench.views.packages.events.LoadedPackageUpdatesEvent;
import org.rstudio.studio.client.workbench.views.packages.events.PackageStatusChangedEvent;
import org.rstudio.studio.client.workbench.views.packages.events.PackageStatusChangedHandler;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInfo;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallContext;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallOptions;
import org.rstudio.studio.client.workbench.views.packages.model.PackageInstallRequest;
import org.rstudio.studio.client.workbench.views.packages.model.PackageLibraryUtils;
import org.rstudio.studio.client.workbench.views.packages.model.PackageState;
import org.rstudio.studio.client.workbench.views.packages.model.PackageStatus;
import org.rstudio.studio.client.workbench.views.packages.model.PackageUpdate;
import org.rstudio.studio.client.workbench.views.packages.model.PackagesServerOperations;
import org.rstudio.studio.client.workbench.views.packages.ui.CheckForUpdatesDialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
public class Packages
extends BasePresenter
implements InstalledPackagesChangedHandler,
PackageStatusChangedHandler,
DeferredInitCompletedEvent.Handler,
PackagesDisplayObserver
{
public interface Binder extends CommandBinder<Commands, Packages> {}
public interface Display extends WorkbenchView
{
void setPackageState(PackratContext packratContext,
List<PackageInfo> packagesDS);
void installPackage(PackageInstallContext installContext,
PackageInstallOptions defaultInstallOptions,
PackagesServerOperations server,
GlobalDisplay globalDisplay,
OperationWithInput<PackageInstallRequest> operation);
void setPackageStatus(PackageStatus status);
void setObserver(PackagesDisplayObserver observer) ;
void setProgress(boolean showProgress);
}
@Inject
public Packages(Display view,
EventBus events,
PackagesServerOperations server,
GlobalDisplay globalDisplay,
Session session,
Binder binder,
Commands commands,
WorkbenchContext workbenchContext,
DefaultCRANMirror defaultCRANMirror)
{
super(view);
view_ = view;
server_ = server;
globalDisplay_ = globalDisplay ;
view_.setObserver(this) ;
events_ = events ;
defaultCRANMirror_ = defaultCRANMirror;
workbenchContext_ = workbenchContext;
session_ = session;
binder.bind(commands, this);
packrat_ = new Packrat(view);
events.addHandler(InstalledPackagesChangedEvent.TYPE, this);
events.addHandler(PackageStatusChangedEvent.TYPE, this);
events.addHandler(DeferredInitCompletedEvent.TYPE, this);
// make the install options persistent
new JSObjectStateValue("packages-pane", "installOptions", ClientState.PROJECT_PERSISTENT,
session.getSessionInfo().getClientState(), false)
{
@Override
protected void onInit(JsObject value)
{
if (value != null)
installOptions_ = value.cast();
lastKnownState_ = installOptions_;
}
@Override
protected JsObject getValue()
{
return installOptions_.cast();
}
@Override
protected boolean hasChanged()
{
if (!PackageInstallOptions.areEqual(lastKnownState_, installOptions_))
{
lastKnownState_ = installOptions_;
return true;
}
return false;
}
private PackageInstallOptions lastKnownState_;
};
updatePackageState();
}
void onInstallPackage()
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
if (installContext.isDefaultLibraryWriteable())
{
continueInstallPackage(installContext);
}
else
{
globalDisplay_.showYesNoMessage(MessageDialog.QUESTION,
"Create Package Library",
"Would you like to create a personal library '" +
installContext.getDefaultUserLibraryPath() + "' " +
"to install packages into?",
false,
new Operation() // Yes operation
{
@Override
public void execute()
{
ProgressIndicator indicator =
globalDisplay_.getProgressIndicator(
"Error Creating Library");
server_.initDefaultUserLibrary(
new VoidServerRequestCallback(indicator) {
@Override
protected void onSuccess()
{
// call this function back recursively
// so we can retrieve the updated
// PackageInstallContext from the server
onInstallPackage();
}
});
}
},
new Operation() // No operation
{
@Override
public void execute()
{
globalDisplay_.showMessage(
MessageDialog.WARNING,
"Install Packages",
"Unable to install packages (default library '" +
installContext.getDefaultLibraryPath() + "' is " +
"not writeable)");
}
},
true);
}
}
});
}
private void continueInstallPackage(
final PackageInstallContext installContext)
{
// if CRAN needs to be configured then do it
if (!installContext.isCRANMirrorConfigured())
{
defaultCRANMirror_.configure(new Command() {
public void execute()
{
doInstallPackage(installContext);
}
});
}
else
{
doInstallPackage(installContext);
}
}
private void doInstallPackage(final PackageInstallContext installContext)
{
// if install options have not yet initialized the default library
// path then set it now from the context
if (StringUtil.isNullOrEmpty(installOptions_.getLibraryPath()))
{
installOptions_ = PackageInstallOptions.create(
installOptions_.getInstallFromRepository(),
installContext.getDefaultLibraryPath(),
installOptions_.getInstallDependencies());
}
view_.installPackage(
installContext,
installOptions_,
server_,
globalDisplay_,
new OperationWithInput<PackageInstallRequest>()
{
public void execute(PackageInstallRequest request)
{
installOptions_ = request.getOptions();
boolean usingDefaultLibrary =
request.getOptions().getLibraryPath().equals(
installContext.getDefaultLibraryPath());
StringBuilder command = new StringBuilder();
command.append("install.packages(");
List<String> packages = request.getPackages();
if (packages != null)
{
if (packages.size() > 1)
command.append("c(");
for (int i=0; i<packages.size(); i++)
{
if (i > 0)
command.append(", ");
command.append("\"");
command.append(packages.get(i));
command.append("\"");
}
if (packages.size() > 1)
command.append(")");
// dependencies
if (!request.getOptions().getInstallDependencies())
command.append(", dependencies = FALSE");
}
// must be a local package
else
{
// get path
FileSystemItem localPackage = request.getLocalPackage();
// convert to string
String path = localPackage.getPath();
// append command
command.append("\"" + path + "\", repos = NULL");
// append type = source if needed
if (path.endsWith(".tar.gz"))
command.append(", type = \"source\"");
}
if (!usingDefaultLibrary)
{
command.append(", lib=\"");
command.append(request.getOptions().getLibraryPath());
command.append("\"");
}
command.append(")");
String cmd = command.toString();
executeWithLoadedPackageCheck(new InstallCommand(packages, cmd));
}
});
}
void onUpdatePackages()
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
// if there are no writeable library paths then we just
// short circuit to all packages are up to date message
if (installContext.getWriteableLibraryPaths().length() == 0)
{
globalDisplay_.showMessage(MessageDialog.INFO,
"Check for Updates",
"All packages are up to date.");
}
// if CRAN needs to be configured then do it
else if (!installContext.isCRANMirrorConfigured())
{
defaultCRANMirror_.configure(new Command() {
public void execute()
{
doUpdatePackages(installContext);
}
});
}
// otherwise we are good to go!
else
{
doUpdatePackages(installContext);
}
}
});
}
private void doUpdatePackages(final PackageInstallContext installContext)
{
new CheckForUpdatesDialog(
globalDisplay_,
new ServerDataSource<JsArray<PackageUpdate>>() {
public void requestData(
ServerRequestCallback<JsArray<PackageUpdate>> requestCallback)
{
server_.checkForPackageUpdates(requestCallback);
}
},
new OperationWithInput<ArrayList<PackageUpdate>>() {
@Override
public void execute(ArrayList<PackageUpdate> updates)
{
InstallCommand cmd = buildUpdatePackagesCommand(updates,
installContext);
executeWithLoadedPackageCheck(cmd);
}
},
new Operation() {
@Override
public void execute()
{
// cancel emits an empty console input line to clear
// the busy indicator
events_.fireEvent(new SendToConsoleEvent("", true));
}
}).showModal();
}
private InstallCommand buildUpdatePackagesCommand(
ArrayList<PackageUpdate> updates,
final PackageInstallContext installContext)
{
// split the updates into their respective target libraries
List<String> packages = new ArrayList<String>();
LinkedHashMap<String, ArrayList<PackageUpdate>> updatesByLibPath =
new LinkedHashMap<String, ArrayList<PackageUpdate>>();
for (PackageUpdate update : updates)
{
// auto-create target list if necessary
String libPath = update.getLibPath();
if (!updatesByLibPath.containsKey(libPath))
updatesByLibPath.put(libPath, new ArrayList<PackageUpdate>());
// insert into list
updatesByLibPath.get(libPath).add(update);
// track global list of packages
packages.add(update.getPackageName());
}
// generate an install packages command for each targeted library
StringBuilder command = new StringBuilder();
for (String libPath : updatesByLibPath.keySet())
{
if (command.length() > 0)
command.append("\n");
ArrayList<PackageUpdate> libPathUpdates = updatesByLibPath.get(libPath);
command.append("install.packages(");
if (libPathUpdates.size() > 1)
command.append("c(");
for (int i=0; i<libPathUpdates.size(); i++)
{
PackageUpdate update = libPathUpdates.get(i);
if (i > 0)
command.append(", ");
command.append("\"");
command.append(update.getPackageName());
command.append("\"");
}
if (libPathUpdates.size() > 1)
command.append(")");
if (!libPath.equals(installContext.getDefaultLibraryPath()))
{
command.append(", lib=\"");
command.append(libPath);
command.append("\"");
}
command.append(")");
}
return new InstallCommand(packages, command.toString());
}
@Handler
public void onRefreshPackages()
{
updatePackageState();
}
public void removePackage(final PackageInfo packageInfo)
{
withPackageInstallContext(new OperationWithInput<PackageInstallContext>(){
@Override
public void execute(final PackageInstallContext installContext)
{
final boolean usingDefaultLibrary = packageInfo.getLibrary().equals(
installContext.getDefaultLibraryPath());
StringBuilder message = new StringBuilder();
message.append("Are you sure you wish to permanently uninstall the '");
message.append(packageInfo.getName() + "' package");
if (!usingDefaultLibrary)
{
message.append(" from library '");
message.append(packageInfo.getLibrary());
message.append("'");
}
message.append("? This action cannot be undone.");
globalDisplay_.showYesNoMessage(
MessageDialog.WARNING,
"Uninstall Package ",
message.toString(),
new Operation()
{
@Override
public void execute()
{
StringBuilder command = new StringBuilder();
command.append("remove.packages(\"");
command.append(packageInfo.getName());
command.append("\"");
if (!usingDefaultLibrary)
{
command.append(", lib=\"");
command.append(packageInfo.getLibrary());
command.append("\"");
}
command.append(")");
String cmd = command.toString();
events_.fireEvent(new SendToConsoleEvent(cmd, true));
}
},
true);
}
});
}
@Override
public void updatePackageState()
{
view_.setProgress(true);
server_.getPackageState(new PackageStateUpdater());
}
public void loadPackage(final String packageName, final String libName)
{
// check status to make sure the package was unloaded
checkPackageStatusOnNextConsolePrompt(packageName, libName);
// send the command
StringBuilder command = new StringBuilder();
command.append("library(\"");
command.append(packageName);
command.append("\"");
command.append(", lib.loc=\"");
command.append(libName);
command.append("\"");
command.append(")");
events_.fireEvent(new SendToConsoleEvent(command.toString(), true));
}
public void unloadPackage(String packageName, String libName)
{
// check status to make sure the package was unloaded
checkPackageStatusOnNextConsolePrompt(packageName, libName);
StringBuilder command = new StringBuilder();
command.append("detach(\"package:");
command.append(packageName);
command.append("\", unload=TRUE)");
events_.fireEvent(new SendToConsoleEvent(command.toString(), true));
}
public void showHelp(PackageInfo packageInfo)
{
events_.fireEvent(new ShowHelpEvent(packageInfo.getUrl())) ;
}
public void onInstalledPackagesChanged(InstalledPackagesChangedEvent event)
{
updatePackageState() ;
}
@Override
public void onDeferredInitCompleted(DeferredInitCompletedEvent event)
{
updatePackageState();
}
public void onPackageFilterChanged(String filter)
{
packageFilter_ = filter.toLowerCase();
setViewPackageList();
}
public void onPackageStatusChanged(PackageStatusChangedEvent event)
{
PackageStatus status = event.getPackageStatus();
view_.setPackageStatus(status);
// also update the list of allPackages_
for (int i = 0; i<allPackages_.size(); i++)
{
PackageInfo packageInfo = allPackages_.get(i);
if (packageInfo.getName().equals(status.getName()) &&
packageInfo.getLibrary().equals(status.getLib()))
{
allPackages_.set(i, status.isLoaded() ? packageInfo.asLoaded() :
packageInfo.asUnloaded());
}
}
}
private void setViewPackageList()
{
ArrayList<PackageInfo> packages = null;
// apply filter (if any)
if (packageFilter_.length() > 0)
{
packages = new ArrayList<PackageInfo>();
// first do prefix search
for (PackageInfo pkgInfo : allPackages_)
{
if (pkgInfo.getName().toLowerCase().startsWith(packageFilter_))
packages.add(pkgInfo);
}
// then do contains search on name & desc
for (PackageInfo pkgInfo : allPackages_)
{
if (pkgInfo.getName().toLowerCase().contains(packageFilter_) ||
pkgInfo.getDesc().toLowerCase().contains(packageFilter_))
{
if (!packages.contains(pkgInfo))
packages.add(pkgInfo);
}
}
}
else
{
packages = allPackages_;
}
view_.setPackageState(packratContext_, packages);
}
private void checkPackageStatusOnNextConsolePrompt(
final String packageName,
final String libName)
{
// remove any existing handler
removeConsolePromptHandler();
consolePromptHandlerReg_ = events_.addHandler(ConsolePromptEvent.TYPE,
new ConsolePromptHandler() {
@Override
public void onConsolePrompt(ConsolePromptEvent event)
{
// remove handler so it is only called once
removeConsolePromptHandler();
// check status and set it
server_.isPackageLoaded(
packageName,
libName,
new ServerRequestCallback<Boolean>() {
@Override
public void onResponseReceived(Boolean status)
{
PackageStatus pkgStatus = PackageStatus.create(packageName,
libName,
status);
view_.setPackageStatus(pkgStatus);
}
@Override
public void onError(ServerError error)
{
// ignore errors
}
});
}
});
}
private void removeConsolePromptHandler()
{
if (consolePromptHandlerReg_ != null)
{
consolePromptHandlerReg_.removeHandler();
consolePromptHandlerReg_ = null;
}
}
private void withPackageInstallContext(
final OperationWithInput<PackageInstallContext> operation)
{
final ProgressIndicator indicator =
globalDisplay_.getProgressIndicator("Error");
indicator.onProgress("Retrieving package installation context...");
server_.getPackageInstallContext(
new SimpleRequestCallback<PackageInstallContext>() {
@Override
public void onResponseReceived(PackageInstallContext context)
{
indicator.onCompleted();
operation.execute(context);
}
@Override
public void onError(ServerError error)
{
indicator.onError(error.getUserMessage());
}
});
}
public void onLoadedPackageUpdates(LoadedPackageUpdatesEvent event)
{
restartForInstallWithConfirmation(event.getInstallCmd());
}
private class InstallCommand
{
public InstallCommand(List<String> packages, String cmd)
{
this.packages = packages;
this.cmd = cmd;
}
public final List<String> packages;
public final String cmd;
}
private void executeWithLoadedPackageCheck(final InstallCommand command)
{
// check if we are potentially going to be overwriting an
// already installed package. if so then prompt for restart
if ((command.packages != null))
{
server_.loadedPackageUpdatesRequired(
command.packages,
new ServerRequestCallback<Boolean>() {
@Override
public void onResponseReceived(Boolean required)
{
if (required)
{
restartForInstallWithConfirmation(command.cmd);
}
else
{
executePkgCommand(command.cmd);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
executePkgCommand(command.cmd);
}
});
}
else
{
executePkgCommand(command.cmd);
}
}
private void executePkgCommand(String cmd)
{
events_.fireEvent(new SendToConsoleEvent(cmd, true));
}
private void restartForInstallWithConfirmation(final String installCmd)
{
String msg = "One or more of the packages that will be updated by this " +
"installation are currently loaded. Restarting R prior " +
"to updating these packages is strongly recommended.\n\n" +
"RStudio can restart R and then automatically continue " +
"the installation after restarting (all work and " +
"data will be preserved during the restart).\n\n" +
"Do you want to restart R prior to installing?";
final boolean haveInstallCmd = installCmd.startsWith("install.packages");
globalDisplay_.showYesNoMessage(
MessageDialog.WARNING,
"Updating Loaded Packages",
msg,
true,
new Operation() { public void execute()
{
events_.fireEvent(new SuspendAndRestartEvent(
SuspendOptions.createSaveAll(true), installCmd));
}},
new Operation() { public void execute()
{
server_.ignoreNextLoadedPackageCheck(
new VoidServerRequestCallback() {
@Override
public void onSuccess()
{
if (haveInstallCmd)
executePkgCommand(installCmd);
}
});
}},
true);
}
private class PackageStateUpdater extends SimpleRequestCallback<PackageState>
{
public PackageStateUpdater()
{
super("Error Listing Packages");
}
@Override
public void onError(ServerError error)
{
// don't show errors during restart
if (!workbenchContext_.isRestartInProgress())
super.onError(error);
view_.setProgress(false);
}
@Override
public void onResponseReceived(PackageState response)
{
// sort the packages
allPackages_ = new ArrayList<PackageInfo>();
JsArray<PackageInfo> serverPackages = response.getPackageList();
for (int i = 0; i < serverPackages.length(); i++)
allPackages_.add(serverPackages.get(i));
Collections.sort(allPackages_, new Comparator<PackageInfo>() {
public int compare(PackageInfo o1, PackageInfo o2)
{
// sort first by library, then by name
int library =
PackageLibraryUtils.typeOfLibrary(
session_, o1.getLibrary()).compareTo(
PackageLibraryUtils.typeOfLibrary(
session_, o2.getLibrary()));
return library == 0 ?
o1.getName().compareToIgnoreCase(o2.getName()) :
library;
}
});
packratContext_ = response.getPackratContext();
view_.setProgress(false);
setViewPackageList();
}
};
private final Display view_;
private final PackagesServerOperations server_;
private ArrayList<PackageInfo> allPackages_ = new ArrayList<PackageInfo>();
private PackratContext packratContext_;
private String packageFilter_ = new String();
private HandlerRegistration consolePromptHandlerReg_ = null;
private final EventBus events_ ;
private final GlobalDisplay globalDisplay_ ;
private final WorkbenchContext workbenchContext_;
private final DefaultCRANMirror defaultCRANMirror_;
private final Session session_;
@SuppressWarnings("unused")
private final Packrat packrat_;
private PackageInstallOptions installOptions_ =
PackageInstallOptions.create(true, "", true);
}
| delay subscribing to the deferreed init completed event in packages pane
| src/gwt/src/org/rstudio/studio/client/workbench/views/packages/Packages.java | delay subscribing to the deferreed init completed event in packages pane | <ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/packages/Packages.java
<ide> import com.google.gwt.core.client.JsArray;
<ide> import com.google.gwt.event.shared.HandlerRegistration;
<ide> import com.google.gwt.user.client.Command;
<add>import com.google.gwt.user.client.Timer;
<ide> import com.google.inject.Inject;
<ide>
<ide> import org.rstudio.core.client.Debug;
<ide>
<ide> @Inject
<ide> public Packages(Display view,
<del> EventBus events,
<add> final EventBus events,
<ide> PackagesServerOperations server,
<ide> GlobalDisplay globalDisplay,
<ide> Session session,
<ide>
<ide> events.addHandler(InstalledPackagesChangedEvent.TYPE, this);
<ide> events.addHandler(PackageStatusChangedEvent.TYPE, this);
<del> events.addHandler(DeferredInitCompletedEvent.TYPE, this);
<ide>
<ide> // make the install options persistent
<ide> new JSObjectStateValue("packages-pane", "installOptions", ClientState.PROJECT_PERSISTENT,
<ide> };
<ide>
<ide> updatePackageState();
<add>
<add> // after 2 seconds also add the DeferredInitCompleted handler
<add> // (we wait because if we don't then on first load in a new
<add> // session where the packages tab is showing updatePackageState
<add> // will be called twice)
<add> new Timer() {
<add> @Override
<add> public void run()
<add> {
<add> events.addHandler(DeferredInitCompletedEvent.TYPE, Packages.this);
<add> }
<add> }.schedule(2000);
<ide> }
<ide>
<ide> void onInstallPackage() |
|
JavaScript | mit | c40b4ed045fc3377212cb54e2b4f9ff4786ac079 | 0 | bieg/independerchat,bieg/independerchat |
'use strict';
const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');
var myDate = new Date();
var groet = '';
/* hour is before noon */
if ( myDate.getHours() < 8 )
{
groet = "Goeiemorgen ��. Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. �� Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen �� naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
groet = "Goeiemorgen �� ";
}
else /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag ��";
}
else /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond ��";
}
else
if (myDate.getHours() > 20 || myDate.getHours() <= 24 )
{
groet = "Goedenavond �� Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. �� Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen �� naar info@independer. Dan komt het altijd goed.";
}
else /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
module.exports = new Script({
processing: {
prompt: (bot) => bot.say(''),
receive: () => 'processing'
},
start: {
receive: (bot,message) => {
const opening = message.text.trim().toUpperCase();
return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
.then(() => bot.say(``))
.then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
.then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
.then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
.then(() => 'selecteerHypotheek');
}
},
selecteerHypotheek: {
receive: (bot, message) => {
switch(message.text) {
case 'Hoi':
return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
.then(() => 'askName')
break;
case 'Starters Hypotheek':
return bot.say(`Wat voor type woning zoek je? `)
.then(() => bot.say(`%[�� Appartement](postback:hypotheekkeuze_appartement) %[�� Huis](postback:hypotheekkeuze_huis) %[�� Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
.then(() => 'woningType')
break;
case 'Nieuwe hypotheek':
return bot.say(`�� Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
.then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[�� Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
.then(() => 'finish')
break;
case 'Hypotheek oversluiten':
return bot.say(`�� Het spijt me maar op dit moment biedt Independer alleen Starters een hypotheek.`)
.then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
.then(() => 'updateOntvangen')
break;
default:
return bot.say(``)
.then(() => 'processing')
break;
}
}
},
updateOntvangen: {
receive: (bot, message) => {
switch(message.text) {
case 'Ja, dat wil ik wel':
return bot.say(`�� Leuk, dan houd ik je op de hoogte zodra er weer nieuws is.`)
.then(() => 'update_ja');
break;
case 'Nee, dat hoeft niet':
receive: () => 'bye'
break;
default:
receive => 'processing'
break;
}
}
},
update_ja: {
prompt: (bot) => bot.say('Wat is je email adres?'),
receive: (bot, message) => {
const emailer=message.text;
return bot.setProp('emailer', emailer)
.then(() => bot.say(`Ok - ✉️ dan hou ik je via ${emailer} op de hoogte.`))
.then(() =>'lastCheck')
}
},
update_nee: {
receive: () => 'bye'
},
hypotheekStarter: {
receive: () => 'askName'
},
hypotheektype_nieuw: {
prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
receive: () => 'processing'
},
woningType: {
receive: (bot, message) => {
switch(message.text) {
case '�� Appartement':
return bot.say(`Nice!`)
.then(() => 'vervolgVragen')
break;
case '�� Huis':
return bot.say(`Leuk`)
.then(() => 'vervolgVragen')
break;
case '�� Vakantiewoning':
return bot.say(`Gezellig`)
.then(() => 'vervolgVragen')
break;
default:
receive => 'processing'
break;
}
}
},
vervolgVragen: {
prompt: (bot) => bot.say('Hoe heet je eigelijk? ��'),
receive: (bot, message) => {
const Name = message.text.trim().toUpperCase();
return bot.setProp('Name', Name)
.then(() => bot.say('Hoi ${Name}. �� Ik heb nog wat vragen voor je om verder te kunnen.'))
.then(() => 'processing')
}
},
lastCheck: {
prompt: (bot) => bot.say(' Is er nog iets waar ik je bij kan helpen? �� %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
receive: (bot, message) => {
switch(message.text) {
case 'Nee hoor':
receive: () => 'bye'
break;
case 'Ik zoek meer informatie':
receive: () => 'speak'
break;
case 'Nee':
receive: () => 'bye'
break;
default:
return bot.say('')
.then(() => 'processing')
break;
}
}
},
meerInfo: {
prompt: (bot) => bot.say(''),
receive: () => 'processing'
},
bye: {
prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
receive: () => 'finish'
},
// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen? Er ging iets mis...'),
// receive: () => ''
// },
finish: {
receive: () => 'finish'
},
speak: {
receive: (bot, message) => {
let upperText = message.text.trim().toUpperCase();
function updateSilent() {
switch (upperText) {
case "CONNECT ME":
return bot.setProp("silent", true);
case "DISCONNECT":
return bot.setProp("silent", false);
default:
return Promise.resolve();
}
}
function getSilent() {
return bot.getProp("silent");
}
function processMessage(isSilent) {
if (isSilent) {
return Promise.resolve("speak");
}
if (!_.has(scriptRules, upperText)) {
return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
}
var response = scriptRules[upperText];
var lines = response.split('\n');
var p = Promise.resolve();
_.each(lines, function(line) {
line = line.trim();
p = p.then(function() {
console.log(line);
return wait(50).then(function() {
return bot.say(line);
});
});
});
return p.then(() => 'speak');
}
return updateSilent()
.then(getSilent)
.then(processMessage);
}
}
});
| script.js |
'use strict';
const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');
var myDate = new Date();
var groet = '';
/* hour is before noon */
if ( myDate.getHours() < 8 )
{
groet = "Goeiemorgen ��. Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. �� Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen �� naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
groet = "Goeiemorgen �� ";
}
else /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag ��";
}
else /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond ��";
}
else
if (myDate.getHours() > 20 || myDate.getHours() <= 24 )
{
groet = "Goedenavond �� Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. �� Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen �� naar info@independer. Dan komt het altijd goed.";
}
else /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
module.exports = new Script({
processing: {
prompt: (bot) => bot.say(''),
receive: () => 'processing'
},
start: {
receive: (bot,message) => {
const opening = message.text.trim().toUpperCase();
return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
.then(() => bot.say(``))
.then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
.then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
.then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
.then(() => 'selecteerHypotheek');
}
},
selecteerHypotheek: {
receive: (bot, message) => {
switch(message.text) {
case 'Hoi':
return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
.then(() => 'askName')
break;
case 'Starters Hypotheek':
return bot.say(`Wat voor type woning zoek je? `)
.then(() => bot.say(`%[�� Appartement](postback:hypotheekkeuze_appartement) %[�� Huis](postback:hypotheekkeuze_huis) %[�� Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
.then(() => 'woningType')
break;
case 'Nieuwe hypotheek':
return bot.say(`�� Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
.then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[�� Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
.then(() => 'finish')
break;
case 'Hypotheek oversluiten':
return bot.say(`�� Het spijt me maar op dit moment biedt Independer alleen Starters een hypotheek.`)
.then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
.then(() => 'updateOntvangen')
break;
default:
return bot.say(``)
.then(() => 'processing')
break;
}
}
},
updateOntvangen: {
receive: (bot, message) => {
switch(message.text) {
case 'Ja, dat wil ik wel':
return bot.say(`�� Leuk, dan houd ik je op de hoogte zodra er weer nieuws is.`)
.then(() => 'update_ja');
break;
case 'Nee, dat hoeft niet':
receive: () => 'bye'
break;
default:
receive => 'processing'
break;
}
}
},
update_ja: {
prompt: (bot) => bot.say('Wat is je email adres?'),
receive: (bot, message) => {
const emailer=message.text;
return bot.setProp('emailer', emailer)
.then(() => bot.say(`Ok - ✉️ dan hou ik je via ${emailer} op de hoogte.`))
.then(() =>'lastCheck')
}
},
update_nee: {
receive: () => 'bye'
},
hypotheekStarter: {
receive: () => 'askName'
},
hypotheektype_nieuw: {
prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
receive: () => 'processing'
},
woningType: {
receive: (bot, message) => {
switch(message.text) {
case '�� Appartement':
return bot.say(`Nice!`)
.then(() => 'vervolgVragen')
break;
case '�� Huis':
return bot.say(`Leuk`)
.then(() => 'vervolgVragen')
break;
case '�� Vakantiewoning':
return bot.say(`Gezellig`)
.then(() => 'vervolgVragen')
break;
default:
receive => 'processing'
break;
}
}
},
vervolgVragen: {
prompt: (bot) => bot.say('Hoe heet je eigelijk? ��'),
receive: (bot, message) => {
const Name = message.text.trim().toUpperCase();
return bot.setProp('Name', Name)
.then(() => bot.say('Hoi ${Name}. �� Ik heb nog wat vragen voor je om verder te kunnen.'))
.then(() => bot.say('komt ie'));
}
},
lastCheck: {
prompt: (bot) => bot.say(' Is er nog iets waar ik je bij kan helpen? �� %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
receive: (bot, message) => {
switch(message.text) {
case 'Nee hoor':
receive: () => 'bye'
break;
case 'Ik zoek meer informatie':
receive: () => 'speak'
break;
case 'Nee':
receive: () => 'bye'
break;
default:
return bot.say('')
.then(() => 'processing')
break;
}
}
},
meerInfo: {
prompt: (bot) => bot.say(''),
receive: () => 'processing'
},
bye: {
prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
receive: () => 'finish'
},
// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen? Er ging iets mis...'),
// receive: () => ''
// },
finish: {
receive: () => 'finish'
},
speak: {
receive: (bot, message) => {
let upperText = message.text.trim().toUpperCase();
function updateSilent() {
switch (upperText) {
case "CONNECT ME":
return bot.setProp("silent", true);
case "DISCONNECT":
return bot.setProp("silent", false);
default:
return Promise.resolve();
}
}
function getSilent() {
return bot.getProp("silent");
}
function processMessage(isSilent) {
if (isSilent) {
return Promise.resolve("speak");
}
if (!_.has(scriptRules, upperText)) {
return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
}
var response = scriptRules[upperText];
var lines = response.split('\n');
var p = Promise.resolve();
_.each(lines, function(line) {
line = line.trim();
p = p.then(function() {
console.log(line);
return wait(50).then(function() {
return bot.say(line);
});
});
});
return p.then(() => 'speak');
}
return updateSilent()
.then(getSilent)
.then(processMessage);
}
}
});
| efq
elf
| script.js | efq | <ide><path>cript.js
<ide> const Name = message.text.trim().toUpperCase();
<ide> return bot.setProp('Name', Name)
<ide> .then(() => bot.say('Hoi ${Name}. �� Ik heb nog wat vragen voor je om verder te kunnen.'))
<del> .then(() => bot.say('komt ie'));
<add> .then(() => 'processing')
<ide> }
<ide> },
<ide> |
|
Java | apache-2.0 | 1479e9e049444ca8714d4f31269e66ac06c9e709 | 0 | taehwandev/BlogExample,taehwandev/BlogExample,taehwandev/Android-BlogExample | package tech.thdev.webviewjavascriptinterface.view.main;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.espresso.web.webdriver.DriverAtoms;
import android.support.test.espresso.web.webdriver.Locator;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import tech.thdev.webviewjavascriptinterface.R;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.web.assertion.WebViewAssertions.webContent;
import static android.support.test.espresso.web.assertion.WebViewAssertions.webMatches;
import static android.support.test.espresso.web.matcher.DomMatchers.hasElementWithId;
import static android.support.test.espresso.web.model.Atoms.castOrDie;
import static android.support.test.espresso.web.model.Atoms.getCurrentUrl;
import static android.support.test.espresso.web.model.Atoms.script;
import static android.support.test.espresso.web.sugar.Web.onWebView;
import static android.support.test.espresso.web.webdriver.DriverAtoms.clearElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.findElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.getText;
import static android.support.test.espresso.web.webdriver.DriverAtoms.webClick;
import static org.hamcrest.Matchers.containsString;
/**
* Created by Tae-hwan on 8/9/16.
* <p>
* - https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/sample/src/androidTest/java/android/support/test/testapp/WebViewTest.java
* - http://blog.egorand.me/testing-runtime-permissions-lessons-learned/
*/
@RunWith(AndroidJUnit4.class)
public class MainFragmentTest {
private static final String ANDROID_SCRIPT_CALL = "EditText keyword change";
private static final String JAVASCRIPT_CALL = "Web text change";
@Rule
public IntentsTestRule<MainActivity> rule = new IntentsTestRule<>(MainActivity.class);
private UiDevice device;
@Before
public void setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
@Test
public void testHasElement() throws Exception {
waitWebViewLoad();
onWebView()
.check(webContent(hasElementWithId("search_keyword")))
.check(webContent(hasElementWithId("updateKeywordBtn")))
.check(webContent(hasElementWithId("showAlertBtn")))
.check(webContent(hasElementWithId("message")));
}
@Test
public void testWebToAndroidScriptCall() throws Exception {
String go = MainFragment.DEFAULT_URL;
onView(withId(R.id.et_url)).perform(clearText());
onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
waitWebViewLoad();
onWebView()
// Find the search keyword element by ID
.withElement(findElement(Locator.ID, "search_keyword"))
// Clear previous input
.perform(clearElement())
// Enter text into the input element
.perform(DriverAtoms.webKeys(ANDROID_SCRIPT_CALL))
// Value check. script getValue 'search_keyword'
.check(webMatches(script("return document.getElementById('search_keyword').value", castOrDie(String.class)), containsString(ANDROID_SCRIPT_CALL)))
// Find the submit button
.withElement(findElement(Locator.ID, "updateKeywordBtn"))
// Simulate a click via javascript
.perform(webClick());
onView(withId(R.id.et_keyword)).check(matches(withText(ANDROID_SCRIPT_CALL)));
}
@Test
public void testWebViewUpdateElementByInputText() throws Exception {
String go = MainFragment.DEFAULT_URL;
onView(withId(R.id.et_url)).perform(clearText());
onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
waitWebViewLoad();
onView(withId(R.id.et_keyword)).perform(clearText()).perform(typeText(JAVASCRIPT_CALL));
onView(withId(R.id.btn_search)).perform(click());
onWebView()
//I use this to allow all needed time to WebView to load
.withNoTimeout()
// Find the message element by ID
.check(webContent(hasElementWithId("search_keyword")))
.check(webMatches(script("return document.getElementById('search_keyword').value", castOrDie(String.class)), containsString(JAVASCRIPT_CALL)));
}
@Test
public void testWebViewUpdateElementByDisplayed() throws Exception {
String go = MainFragment.DEFAULT_URL;
onView(withId(R.id.et_url)).perform(clearText());
onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
waitWebViewLoad();
onView(withId(R.id.et_keyword)).perform(clearText()).perform(typeText(JAVASCRIPT_CALL));
onView(withId(R.id.btn_search)).perform(click());
onWebView()
//I use this to allow all needed time to WebView to load
.withNoTimeout()
// Find the message element by ID
.check(webContent(hasElementWithId("search_keyword")))
// Find the message element by ID
.withElement(findElement(Locator.ID, "message"))
// Verify that the text is displayed
.check(webMatches(getText(), containsString(JAVASCRIPT_CALL)));
}
@Test
public void testShowAlertDialog() throws Throwable {
// create a signal to let us know when our task is done.
final CountDownLatch signal = new CountDownLatch(1);
waitWebViewLoad();
new Thread(new Runnable() {
@Override
public void run() {
try {
// Wait second
signal.await(1, TimeUnit.SECONDS);
// Find ok button and click
assertViewWithTextIsVisible(device, rule.getActivity().getString(android.R.string.ok));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// WebView show alert dialog
onWebView().withElement(findElement(Locator.ID, "showAlertBtn"))
.perform(webClick());
}
/**
* WebView load finish check.
*/
private void waitWebViewLoad() throws Exception {
onWebView()
.withNoTimeout()
// Check current url
.check(webMatches(getCurrentUrl(), containsString(MainFragment.DEFAULT_URL)));
}
public static void assertViewWithTextIsVisible(UiDevice device, String text) throws UiObjectNotFoundException {
UiObject allowButton = device.findObject(new UiSelector().text(text));
if (!allowButton.exists()) {
throw new AssertionError("View with text <" + text + "> not found!");
}
allowButton.click();
}
} | WebViewJavascriptInterafce/src/androidTest/java/tech/thdev/webviewjavascriptinterface/view/main/MainFragmentTest.java | package tech.thdev.webviewjavascriptinterface.view.main;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.espresso.web.webdriver.DriverAtoms;
import android.support.test.espresso.web.webdriver.Locator;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import tech.thdev.webviewjavascriptinterface.R;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.web.assertion.WebViewAssertions.webContent;
import static android.support.test.espresso.web.assertion.WebViewAssertions.webMatches;
import static android.support.test.espresso.web.matcher.DomMatchers.hasElementWithId;
import static android.support.test.espresso.web.model.Atoms.getCurrentUrl;
import static android.support.test.espresso.web.sugar.Web.onWebView;
import static android.support.test.espresso.web.webdriver.DriverAtoms.clearElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.findElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.getText;
import static android.support.test.espresso.web.webdriver.DriverAtoms.webClick;
import static org.hamcrest.Matchers.containsString;
/**
* Created by Tae-hwan on 8/9/16.
* <p>
* - https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/sample/src/androidTest/java/android/support/test/testapp/WebViewTest.java
* - http://blog.egorand.me/testing-runtime-permissions-lessons-learned/
*/
@RunWith(AndroidJUnit4.class)
public class MainFragmentTest {
private static final String ANDROID_SCRIPT_CALL = "EditText keyword change";
private static final String JAVASCRIPT_CALL = "Web text change";
@Rule
public IntentsTestRule<MainActivity> rule = new IntentsTestRule<>(MainActivity.class);
private UiDevice device;
// create a signal to let us know when our task is done.
private final CountDownLatch signal = new CountDownLatch(1);
@Before
public void setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
@Test
public void testHasElement() throws Exception {
waitWebViewLoad();
onWebView()
.check(webContent(hasElementWithId("search_keyword")))
.check(webContent(hasElementWithId("updateKeywordBtn")))
.check(webContent(hasElementWithId("showAlertBtn")))
.check(webContent(hasElementWithId("message")));
}
@Test
public void testWebToAndroidScriptCall() throws Exception {
String go = MainFragment.DEFAULT_URL;
onView(withId(R.id.et_url)).perform(clearText());
onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
waitWebViewLoad();
onWebView()
// Find the search keyword element by ID
.withElement(findElement(Locator.ID, "search_keyword"))
// Clear previous input
.perform(clearElement())
// Enter text into the input element
.perform(DriverAtoms.webKeys(ANDROID_SCRIPT_CALL))
// Find the submit button
.withElement(findElement(Locator.ID, "updateKeywordBtn"))
// Simulate a click via javascript
.perform(webClick());
onView(withId(R.id.et_keyword)).check(matches(withText(ANDROID_SCRIPT_CALL)));
}
@Test
public void testAndroidToWebScriptCall() throws Exception {
String go = MainFragment.DEFAULT_URL;
onView(withId(R.id.et_url)).perform(clearText());
onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
waitWebViewLoad();
onView(withId(R.id.et_keyword)).perform(clearText()).perform(typeText(JAVASCRIPT_CALL));
onView(withId(R.id.btn_search)).perform(click());
onWebView()
//I use this to allow all needed time to WebView to load
.withNoTimeout()
// Find the message element by ID
.check(webContent(hasElementWithId("message")))
// Find the message element by ID
.withElement(findElement(Locator.ID, "message"))
// Verify that the text is displayed
.check(webMatches(getText(), containsString(JAVASCRIPT_CALL)));
}
@Test
public void testShowAlertDialog() throws Throwable {
waitWebViewLoad();
new Thread(new Runnable() {
@Override
public void run() {
try {
// Wait 2 second
signal.await(2, TimeUnit.SECONDS);
// Find ok button and click
assertViewWithTextIsVisible(device, rule.getActivity().getString(android.R.string.ok));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// WebView show alert dialog
onWebView().withElement(findElement(Locator.ID, "showAlertBtn"))
.perform(webClick());
}
private void waitWebViewLoad() {
onWebView()
.withNoTimeout()
// Check current url
.check(webMatches(getCurrentUrl(), containsString(MainFragment.DEFAULT_URL)));
}
public static void assertViewWithTextIsVisible(UiDevice device, String text) throws UiObjectNotFoundException {
UiObject allowButton = device.findObject(new UiSelector().text(text));
if (!allowButton.exists()) {
throw new AssertionError("View with text <" + text + "> not found!");
}
allowButton.click();
}
} | WebView Javascript example.
- update WebView UnitTest
| WebViewJavascriptInterafce/src/androidTest/java/tech/thdev/webviewjavascriptinterface/view/main/MainFragmentTest.java | WebView Javascript example. - update WebView UnitTest | <ide><path>ebViewJavascriptInterafce/src/androidTest/java/tech/thdev/webviewjavascriptinterface/view/main/MainFragmentTest.java
<ide> import static android.support.test.espresso.web.assertion.WebViewAssertions.webContent;
<ide> import static android.support.test.espresso.web.assertion.WebViewAssertions.webMatches;
<ide> import static android.support.test.espresso.web.matcher.DomMatchers.hasElementWithId;
<add>import static android.support.test.espresso.web.model.Atoms.castOrDie;
<ide> import static android.support.test.espresso.web.model.Atoms.getCurrentUrl;
<add>import static android.support.test.espresso.web.model.Atoms.script;
<ide> import static android.support.test.espresso.web.sugar.Web.onWebView;
<ide> import static android.support.test.espresso.web.webdriver.DriverAtoms.clearElement;
<ide> import static android.support.test.espresso.web.webdriver.DriverAtoms.findElement;
<ide> public IntentsTestRule<MainActivity> rule = new IntentsTestRule<>(MainActivity.class);
<ide>
<ide> private UiDevice device;
<del>
<del> // create a signal to let us know when our task is done.
<del> private final CountDownLatch signal = new CountDownLatch(1);
<ide>
<ide> @Before
<ide> public void setUp() {
<ide> .perform(clearElement())
<ide> // Enter text into the input element
<ide> .perform(DriverAtoms.webKeys(ANDROID_SCRIPT_CALL))
<add> // Value check. script getValue 'search_keyword'
<add> .check(webMatches(script("return document.getElementById('search_keyword').value", castOrDie(String.class)), containsString(ANDROID_SCRIPT_CALL)))
<ide> // Find the submit button
<ide> .withElement(findElement(Locator.ID, "updateKeywordBtn"))
<ide> // Simulate a click via javascript
<ide> }
<ide>
<ide> @Test
<del> public void testAndroidToWebScriptCall() throws Exception {
<add> public void testWebViewUpdateElementByInputText() throws Exception {
<ide> String go = MainFragment.DEFAULT_URL;
<ide>
<ide> onView(withId(R.id.et_url)).perform(clearText());
<ide> //I use this to allow all needed time to WebView to load
<ide> .withNoTimeout()
<ide> // Find the message element by ID
<del> .check(webContent(hasElementWithId("message")))
<add> .check(webContent(hasElementWithId("search_keyword")))
<add> .check(webMatches(script("return document.getElementById('search_keyword').value", castOrDie(String.class)), containsString(JAVASCRIPT_CALL)));
<add> }
<add>
<add> @Test
<add> public void testWebViewUpdateElementByDisplayed() throws Exception {
<add> String go = MainFragment.DEFAULT_URL;
<add>
<add> onView(withId(R.id.et_url)).perform(clearText());
<add> onView(withId(R.id.et_url)).perform(typeText(go)).perform(ViewActions.pressImeActionButton());
<add>
<add> waitWebViewLoad();
<add>
<add> onView(withId(R.id.et_keyword)).perform(clearText()).perform(typeText(JAVASCRIPT_CALL));
<add> onView(withId(R.id.btn_search)).perform(click());
<add>
<add> onWebView()
<add> //I use this to allow all needed time to WebView to load
<add> .withNoTimeout()
<add> // Find the message element by ID
<add> .check(webContent(hasElementWithId("search_keyword")))
<ide> // Find the message element by ID
<ide> .withElement(findElement(Locator.ID, "message"))
<ide> // Verify that the text is displayed
<ide>
<ide> @Test
<ide> public void testShowAlertDialog() throws Throwable {
<add> // create a signal to let us know when our task is done.
<add> final CountDownLatch signal = new CountDownLatch(1);
<add>
<ide> waitWebViewLoad();
<ide>
<ide> new Thread(new Runnable() {
<ide> @Override
<ide> public void run() {
<ide> try {
<del> // Wait 2 second
<del> signal.await(2, TimeUnit.SECONDS);
<add> // Wait second
<add> signal.await(1, TimeUnit.SECONDS);
<ide> // Find ok button and click
<ide> assertViewWithTextIsVisible(device, rule.getActivity().getString(android.R.string.ok));
<ide> } catch (Exception e) {
<ide> .perform(webClick());
<ide> }
<ide>
<del> private void waitWebViewLoad() {
<add> /**
<add> * WebView load finish check.
<add> */
<add> private void waitWebViewLoad() throws Exception {
<ide> onWebView()
<ide> .withNoTimeout()
<ide> // Check current url |
|
JavaScript | mit | e689c26b17ab398643f54daee728d1ead4bb0824 | 0 | adrian-castravete/amber,amber-smalltalk/amber,amber-smalltalk/amber,adrian-castravete/amber,matthias-springer/amber-athens,matthias-springer/amber-athens,adrian-castravete/amber,amber-smalltalk/amber,matthias-springer/amber-athens | /* ====================================================================
|
| Amber Smalltalk
| http://amber-lang.net
|
======================================================================
======================================================================
|
| Copyright (c) 2010-2011
| Nicolas Petton <[email protected]>
|
| Amber is released under the MIT license
|
| 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.
|
==================================================================== */
/* Make sure that console is defined */
if(typeof console === "undefined") {
this.console = {
log: function() {},
warn: function() {},
info: function() {},
debug: function() {},
error: function() {}
};
}
/* Array extensions */
Array.prototype.addElement = function(el) {
if(typeof el === 'undefined') { return; }
if(this.indexOf(el) == -1) {
this.push(el);
}
};
Array.prototype.removeElement = function(el) {
var i = this.indexOf(el);
if (i !== -1) { this.splice(i, 1); }
};
/* Smalltalk constructors definition */
function SmalltalkObject() {}
function SmalltalkBehavior() {}
function SmalltalkClass() {}
function SmalltalkMetaclass() {
this.meta = true;
}
function SmalltalkPackage() {}
function SmalltalkMethod() {}
function SmalltalkNil() {}
function SmalltalkSymbol(string) {
this.value = string;
}
function SmalltalkOrganizer() {
this.elements = [];
}
function inherits(child, parent) {
child.prototype = Object.create(parent.prototype, {
constructor: { value: child,
enumerable: false, configurable: true, writable: true }
});
}
inherits(SmalltalkBehavior, SmalltalkObject);
inherits(SmalltalkClass, SmalltalkBehavior);
inherits(SmalltalkMetaclass, SmalltalkBehavior);
inherits(SmalltalkNil, SmalltalkObject);
inherits(SmalltalkMethod, SmalltalkObject);
inherits(SmalltalkPackage, SmalltalkObject);
inherits(SmalltalkOrganizer, SmalltalkObject);
function Smalltalk() {
var st = this;
/* This is the current call context object. While it is publicly available,
Use smalltalk.getThisContext() instead which will answer a safe copy of
the current context */
st.thisContext = undefined;
/* List of all reserved words in JavaScript. They may not be used as variables
in Smalltalk. */
// list of reserved JavaScript keywords as of
// http://es5.github.com/#x7.6.1.1
// and
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
'try', 'typeof', 'var', 'void', 'while', 'with',
// ES5: future use: http://es5.github.com/#x7.6.1.2
'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
// ES5: future use in strict mode
'implements', 'interface', 'let', 'package', 'private', 'protected',
'public', 'static', 'yield'];
var initialized = false;
/* Smalltalk classes */
var classes = [];
var wrappedClasses = [];
/* Method not implemented handlers */
var dnu = {
methods: [],
selectors: [],
get: function (string) {
var index = this.selectors.indexOf(string);
if(index !== -1) {
return this.methods[index];
}
this.selectors.push(string);
var selector = st.selector(string);
var method = {jsSelector: selector, fn: this.createHandler(selector)};
this.methods.push(method);
return method;
},
/* Dnu handler method */
createHandler: function (selector) {
return function () {
var args = Array.prototype.slice.call(arguments);
return messageNotUnderstood(this, selector, args);
};
}
};
/* The symbol table ensures symbol unicity */
var symbolTable = {};
st.symbolFor = function(string) {
if(symbolTable[string] === undefined) {
symbolTable[string] = new SmalltalkSymbol(string);
}
return symbolTable[string];
};
/* Unique ID number generator */
var oid = 0;
st.nextId = function() {
oid += 1;
return oid;
};
/* We hold all Packages in a separate Object */
st.packages = {};
/* Smalltalk package creation. To add a Package, use smalltalk.addPackage() */
function pkg(spec) {
var that = new SmalltalkPackage();
that.pkgName = spec.pkgName;
that.organization = new SmalltalkOrganizer();
that.properties = spec.properties || {};
return that;
}
/* Smalltalk class creation. A class is an instance of an automatically
created metaclass object. Newly created classes (not their metaclass)
should be added to the smalltalk object, see smalltalk.addClass().
Superclass linking is *not* handled here, see smalltalk.init() */
function klass(spec) {
spec = spec || {};
var meta = metaclass(spec);
var that = meta.instanceClass;
that.fn = spec.fn || function() {};
setupClass(that, spec);
that.className = spec.className;
that.wrapped = spec.wrapped || false;
meta.className = spec.className + ' class';
if(spec.superclass) {
that.superclass = spec.superclass;
meta.superclass = spec.superclass.klass;
}
return that;
}
function metaclass(spec) {
spec = spec || {};
var that = new SmalltalkMetaclass();
inherits(
that.fn = function() {},
spec.superclass ? spec.superclass.klass.fn : SmalltalkClass
);
that.instanceClass = new that.fn();
setupClass(that);
return that;
}
function setupClass(klass, spec) {
spec = spec || {};
klass.iVarNames = spec.iVarNames || [];
klass.pkg = spec.pkg;
Object.defineProperty(klass, "toString", {
value: function() { return 'Smalltalk ' + this.className; },
enumerable:false, configurable: true, writable: false
});
klass.organization = new SmalltalkOrganizer();
Object.defineProperty(klass, "methods", {
value: {},
enumerable: false, configurable: true, writable: true
});
wireKlass(klass);
}
/* Smalltalk method object. To add a method to a class,
use smalltalk.addMethod() */
st.method = function(spec) {
var that = new SmalltalkMethod();
that.selector = spec.selector;
that.jsSelector = spec.jsSelector;
that.args = spec.args || {};
that.category = spec.category;
that.source = spec.source;
that.messageSends = spec.messageSends || [];
that.referencedClasses = spec.referencedClasses || [];
that.fn = spec.fn;
return that;
};
/* Initialize a class in its class hierarchy. Handle both classes and
metaclasses. */
st.init = function(klass) {
st.initClass(klass);
if(klass.klass && !klass.meta) {
st.initClass(klass.klass);
}
};
st.initClass = function(klass) {
if(klass.wrapped) {
copySuperclass(klass);
}
else {
installSuperclass(klass);
}
if(klass === st.Object || klass.wrapped) {
installDnuHandlers(klass);
}
};
function wireKlass(klass) {
Object.defineProperty(klass.fn.prototype, "klass", {
value: klass,
enumerable: false, configurable: true, writable: true
});
}
function installSuperclass(klass) {
// only if the klass has not been initialized yet.
if(klass.fn.prototype._yourself) { return; }
if(klass.superclass && klass.superclass !== nil) {
inherits(klass.fn, klass.superclass.fn);
wireKlass(klass);
reinstallMethods(klass);
}
}
function copySuperclass(klass, superclass) {
for (superclass = superclass || klass.superclass;
superclass && superclass !== nil;
superclass = superclass.superclass) {
for (var keys = Object.keys(superclass.methods), i = 0; i < keys.length; i++) {
installMethodIfAbsent(superclass.methods[keys[i]], klass);
}
}
}
function installMethod(method, klass) {
Object.defineProperty(klass.fn.prototype, method.jsSelector, {
value: method.fn,
enumerable: false, configurable: true, writable: true
});
}
function installMethodIfAbsent(method, klass) {
if(!klass.fn.prototype[method.jsSelector]) {
installMethod(method, klass);
}
}
function reinstallMethods(klass) {
for(var keys = Object.keys(klass.methods), i=0; i<keys.length; i++) {
installMethod(klass.methods[keys[i]], klass);
}
}
function installDnuHandlers(klass) {
var m = dnu.methods;
for(var i=0; i<m.length; i++) {
installMethodIfAbsent(m[i], klass);
}
}
function installNewDnuHandler(newHandler) {
installMethodIfAbsent(newHandler, st.Object);
for(var i = 0; i < wrappedClasses.length; i++) {
installMethodIfAbsent(newHandler, wrappedClasses[i]);
}
}
/* Answer all registered Packages as Array */
// TODO: Remove this hack
st.packages.all = function() {
var packages = [];
for(var i in st.packages) {
if(!st.packages.hasOwnProperty(i) || typeof(st.packages[i]) === "function") continue;
packages.push(st.packages[i]);
}
return packages
};
/* Answer all registered Smalltalk classes */
//TODO: remove the function and make smalltalk.classes an array
st.classes = function() {
return classes;
};
st.wrappedClasses = function() {
return wrappedClasses;
};
/* Answer the direct subclasses of klass. */
st.subclasses = function(klass) {
var subclasses = [];
var classes = st.classes();
for(var i=0; i < classes.length; i++) {
var c = classes[i];
if(c.fn) {
//Classes
if(c.superclass === klass) {
subclasses.push(c);
}
c = c.klass;
//Metaclasses
if(c && c.superclass === klass) {
subclasses.push(c);
}
}
}
return subclasses;
};
/* Create a new class wrapping a JavaScript constructor, and add it to the
global smalltalk object. Package is lazily created if it does not exist with given name. */
st.wrapClassName = function(className, pkgName, fn, superclass, wrapped) {
if(wrapped !== false) {
wrapped = true;
}
var pkg = st.addPackage(pkgName);
st[className] = klass({
className: className,
superclass: superclass,
pkg: pkg,
fn: fn,
wrapped: wrapped
});
classes.addElement(st[className]);
if(wrapped) {wrappedClasses.addElement(st[className])}
pkg.organization.elements.addElement(st[className]);
};
/* Create an alias for an existing class */
st.alias = function(klass, alias) {
st[alias] = klass;
};
/* Add a package to the smalltalk.packages object, creating a new one if needed.
If pkgName is null or empty we return nil, which is an allowed package for a class.
If package already exists we still update the properties of it. */
st.addPackage = function(pkgName, properties) {
if(!pkgName) {return nil;}
if(!(st.packages[pkgName])) {
st.packages[pkgName] = pkg({
pkgName: pkgName,
properties: properties
});
} else {
if(properties) {
st.packages[pkgName].properties = properties;
}
}
return st.packages[pkgName];
};
/* Add a class to the smalltalk object, creating a new one if needed.
A Package is lazily created if it does not exist with given name. */
st.addClass = function(className, superclass, iVarNames, pkgName) {
var pkg = st.addPackage(pkgName);
if (superclass == nil) { superclass = null; }
if(st[className] && st[className].superclass == superclass) {
st[className].superclass = superclass;
st[className].iVarNames = iVarNames;
st[className].pkg = pkg || st[className].pkg;
} else {
if(st[className]) {
st.removeClass(st[className]);
}
st[className] = klass({
className: className,
superclass: superclass,
pkg: pkg,
iVarNames: iVarNames
});
}
classes.addElement(st[className]);
pkg.organization.elements.addElement(st[className]);
};
st.removeClass = function(klass) {
klass.pkg.organization.elements.removeElement(klass);
classes.removeElement(klass);
delete st[klass.className];
};
/* Add/remove a method to/from a class */
st.addMethod = function(jsSelector, method, klass) {
method.jsSelector = jsSelector;
installMethod(method, klass);
klass.methods[method.selector] = method;
method.methodClass = klass;
klass.organization.elements.addElement(method.category);
for(var i=0; i<method.messageSends.length; i++) {
var dnuHandler = dnu.get(method.messageSends[i]);
if(initialized) {
installNewDnuHandler(dnuHandler);
}
}
};
st.removeMethod = function(method) {
var protocol = method.category;
var klass = method.methodClass;
delete klass.fn.prototype[st.selector(method.selector)];
delete klass.methods[method.selector];
var selectors = Object.keys(klass.methods);
var shouldDeleteProtocol = true;
for(var i = 0, l = selectors.length; i<l; i++) {
if(klass.methods[selectors[i]].category === protocol) {
shouldDeleteProtocol = false;
break;
};
};
if(shouldDeleteProtocol) {
klass.organization.elements.removeElement(protocol)
};
};
/* Handles unhandled errors during message sends */
// simply send the message and handle #dnu:
st.send = function(receiver, selector, args, klass) {
var method;
if(receiver == null) {
receiver = nil;
}
method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
if(method) {
return method.apply(receiver, args);
} else {
return messageNotUnderstood(receiver, selector, args);
}
}
st.withContext = function(worker, setup) {
if(st.thisContext) {
st.thisContext.pc++;
return inContext(worker, setup);
} else {
try {return inContext(worker, setup)}
catch(error) {
// Reset the context stack in any case
st.thisContext = undefined;
if(error.smalltalkError) {
handleError(error);
return nil;
} else {
throw(error);
}
}
}
};
function inContext(worker, setup) {
var context = pushContext(setup);
var result = worker(context);
popContext(context);
return result;
}
/* Handles Smalltalk errors. Triggers the registered ErrorHandler
(See the Smalltalk class ErrorHandler and its subclasses */
function handleError(error) {
st.ErrorHandler._current()._handleError_(error);
}
/* Handles #dnu: *and* JavaScript method calls.
if the receiver has no klass, we consider it a JS object (outside of the
Amber system). Else assume that the receiver understands #doesNotUnderstand: */
function messageNotUnderstood(receiver, selector, args) {
/* Handles JS method calls. */
if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
return callJavaScriptMethod(receiver, selector, args);
}
/* Handles not understood messages. Also see the Amber counter-part
Object>>doesNotUnderstand: */
return receiver._doesNotUnderstand_(
st.Message._new()
._selector_(st.convertSelector(selector))
._arguments_(args)
);
}
/* Call a method of a JS object, or answer a property if it exists.
Else try wrapping a JSObjectProxy around the receiver.
If the object property is a function, then call it, except if it starts with
an uppercase character (we probably want to answer the function itself in this
case and send it #new from Amber).
Converts keyword-based selectors by using the first
keyword only, but keeping all message arguments.
Example:
"self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
function callJavaScriptMethod(receiver, selector, args) {
var jsSelector = selector._asJavaScriptSelector();
var jsProperty = receiver[jsSelector];
if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
return jsProperty.apply(receiver, args);
} else if(jsProperty !== undefined) {
if(args[0]) {
receiver[jsSelector] = args[0];
return nil;
} else {
return jsProperty;
}
}
return st.send(st.JSObjectProxy._on_(receiver), selector, args);
}
/* Handle thisContext pseudo variable */
st.getThisContext = function() {
if(st.thisContext) {
st.thisContext.init();
return st.thisContext;
} else {
return nil;
}
};
function pushContext(setup) {
return st.thisContext = new SmalltalkMethodContext(smalltalk.thisContext, setup);
}
function popContext(context) {
st.thisContext = context.homeContext;
}
/* Convert a Smalltalk selector into a JS selector */
st.selector = function(string) {
var selector = '_' + string;
selector = selector.replace(/:/g, '_');
selector = selector.replace(/[\&]/g, '_and');
selector = selector.replace(/[\|]/g, '_or');
selector = selector.replace(/[+]/g, '_plus');
selector = selector.replace(/-/g, '_minus');
selector = selector.replace(/[*]/g ,'_star');
selector = selector.replace(/[\/]/g ,'_slash');
selector = selector.replace(/[\\]/g ,'_backslash');
selector = selector.replace(/[\~]/g ,'_tild');
selector = selector.replace(/>/g ,'_gt');
selector = selector.replace(/</g ,'_lt');
selector = selector.replace(/=/g ,'_eq');
selector = selector.replace(/,/g ,'_comma');
selector = selector.replace(/[@]/g ,'_at');
return selector
};
/* Convert a string to a valid smalltalk selector.
if you modify the following functions, also change String>>asSelector
accordingly */
st.convertSelector = function(selector) {
if(selector.match(/__/)) {
return convertBinarySelector(selector);
} else {
return convertKeywordSelector(selector);
}
};
function convertKeywordSelector(selector) {
return selector.replace(/^_/, '').replace(/_/g, ':');
}
function convertBinarySelector(selector) {
return selector
.replace(/^_/, '')
.replace(/_and/g, '&')
.replace(/_or/g, '|')
.replace(/_plus/g, '+')
.replace(/_minus/g, '-')
.replace(/_star/g, '*')
.replace(/_slash/g, '/')
.replace(/_backslash/g, '\\')
.replace(/_tild/g, '~')
.replace(/_gt/g, '>')
.replace(/_lt/g, '<')
.replace(/_eq/g, '=')
.replace(/_comma/g, ',')
.replace(/_at/g, '@')
}
/* Converts a JavaScript object to valid Smalltalk Object */
st.readJSObject = function(js) {
var object = js;
var readObject = (js.constructor === Object);
var readArray = (js.constructor === Array);
if(readObject) {
object = st.Dictionary._new();
}
for(var i in js) {
if(readObject) {
object._at_put_(i, st.readJSObject(js[i]));
}
if(readArray) {
object[i] = st.readJSObject(js[i]);
}
}
return object;
};
/* Boolean assertion */
st.assert = function(shouldBeBoolean) {
if ((undefined !== shouldBeBoolean) && (shouldBeBoolean.klass === smalltalk.Boolean)) {
return shouldBeBoolean == true;
} else {
smalltalk.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
}
};
/* Smalltalk initialization. Called on page load */
st.initialize = function() {
if(initialized) { return; }
classes.forEach(function(klass) {
st.init(klass);
});
classes.forEach(function(klass) {
klass._initialize();
});
initialized = true;
};
}
inherits(Smalltalk, SmalltalkObject);
function SmalltalkMethodContext(home, setup) {
this.homeContext = home;
this.setup = setup || function() {};
this.pc = 0;
this.locals = {};
this.args = [];
}
inherits(SmalltalkMethodContext, SmalltalkObject);
SmalltalkMethodContext.prototype.fill = function(receiver, selector, args, locals, lookupClass) {
this.receiver = receiver;
this.selector = selector;
this.args = args || [];
this.locals = locals || {};
this.lookupClass = lookupClass;
};
SmalltalkMethodContext.prototype.fillBlock = function(args, locals) {
this.receiver = null;
this.selector = null;
this.args = args || [];
this.locals = locals || {};
this.lookupClass = null;
};
SmalltalkMethodContext.prototype.init = function() {
var home = this.homeContext;
if(home) {home = home.init()}
this.setup(this);
};
SmalltalkMethodContext.prototype.method = function() {
var method;
var lookup = this.lookupClass || this.receiver.klass;
while(!method && lookup) {
method = lookup.methods[smalltalk.convertSelector(this.selector)];
lookup = lookup.superclass
}
return method;
};
SmalltalkMethodContext.prototype.resume = function() {
//Brutally set the receiver as thisContext, then re-enter the function
smalltalk.thisContext = this;
return this.method.apply(receiver, temps);
};
/* Global Smalltalk objects. */
var nil = new SmalltalkNil();
var smalltalk = new Smalltalk();
if(this.jQuery) {
this.jQuery.allowJavaScriptCalls = true;
}
/*
* Answer the smalltalk representation of o.
* Used in message sends
*/
var _st = function(o) {
if(o == null) {return nil}
if(o.klass) {return o}
return smalltalk.JSObjectProxy._on_(o);
};
/***************************************** BOOTSTRAP ******************************************/
smalltalk.wrapClassName("Object", "Kernel-Objects", SmalltalkObject, undefined, false);
smalltalk.wrapClassName("Behavior", "Kernel-Classes", SmalltalkBehavior, smalltalk.Object, false);
smalltalk.wrapClassName("Metaclass", "Kernel-Classes", SmalltalkMetaclass, smalltalk.Behavior, false);
smalltalk.wrapClassName("Class", "Kernel-Classes", SmalltalkClass, smalltalk.Behavior, false);
smalltalk.Object.klass.superclass = smalltalk.Class;
smalltalk.wrapClassName("Smalltalk", "Kernel-Objects", Smalltalk, smalltalk.Object, false);
smalltalk.wrapClassName("Package", "Kernel-Objects", SmalltalkPackage, smalltalk.Object, false);
smalltalk.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, smalltalk.Object, false);
smalltalk.wrapClassName("Organizer", "Kernel-Objects", SmalltalkOrganizer, smalltalk.Object, false);
smalltalk.wrapClassName("Number", "Kernel", Number, smalltalk.Object);
smalltalk.wrapClassName("BlockClosure", "Kernel", Function, smalltalk.Object);
smalltalk.wrapClassName("Boolean", "Kernel", Boolean, smalltalk.Object);
smalltalk.wrapClassName("Date", "Kernel", Date, smalltalk.Object);
smalltalk.wrapClassName("UndefinedObject", "Kernel", SmalltalkNil, smalltalk.Object, false);
smalltalk.wrapClassName("Collection", "Kernel", null, smalltalk.Object, false);
smalltalk.wrapClassName("SequenceableCollection", "Kernel", null, smalltalk.Collection, false);
smalltalk.wrapClassName("CharacterArray", "Kernel", null, smalltalk.SequenceableCollection, false);
smalltalk.wrapClassName("String", "Kernel", String, smalltalk.CharacterArray);
smalltalk.wrapClassName("Symbol", "Kernel", SmalltalkSymbol, smalltalk.CharacterArray, false);
smalltalk.wrapClassName("Array", "Kernel", Array, smalltalk.SequenceableCollection);
smalltalk.wrapClassName("RegularExpression", "Kernel", RegExp, smalltalk.String);
smalltalk.wrapClassName("Error", "Kernel", Error, smalltalk.Object);
smalltalk.wrapClassName("MethodContext", "Kernel", SmalltalkMethodContext, smalltalk.Object, false);
/* Alias definitions */
smalltalk.alias(smalltalk.Array, "OrderedCollection");
smalltalk.alias(smalltalk.Date, "Time");
| js/boot.js | /* ====================================================================
|
| Amber Smalltalk
| http://amber-lang.net
|
======================================================================
======================================================================
|
| Copyright (c) 2010-2011
| Nicolas Petton <[email protected]>
|
| Amber is released under the MIT license
|
| 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.
|
==================================================================== */
/* Make sure that console is defined */
if(typeof console === "undefined") {
this.console = {
log: function() {},
warn: function() {},
info: function() {},
debug: function() {},
error: function() {}
};
}
/* Array extensions */
Array.prototype.addElement = function(el) {
if(typeof el === 'undefined') { return; }
if(this.indexOf(el) == -1) {
this.push(el);
}
};
Array.prototype.removeElement = function(el) {
var i = this.indexOf(el);
if (i !== -1) { this.splice(i, 1); }
};
/* Smalltalk constructors definition */
function SmalltalkObject() {}
function SmalltalkBehavior() {}
function SmalltalkClass() {}
function SmalltalkMetaclass() {
this.meta = true;
}
function SmalltalkPackage() {}
function SmalltalkMethod() {}
function SmalltalkNil() {}
function SmalltalkSymbol(string) {
this.value = string;
}
function SmalltalkOrganizer() {
this.elements = [];
}
function inherits(child, parent) {
child.prototype = Object.create(parent.prototype, {
constructor: { value: child,
enumerable: false, configurable: true, writable: true }
});
}
inherits(SmalltalkBehavior, SmalltalkObject);
inherits(SmalltalkClass, SmalltalkBehavior);
inherits(SmalltalkMetaclass, SmalltalkBehavior);
inherits(SmalltalkNil, SmalltalkObject);
inherits(SmalltalkMethod, SmalltalkObject);
inherits(SmalltalkPackage, SmalltalkObject);
inherits(SmalltalkOrganizer, SmalltalkObject);
function Smalltalk() {
var st = this;
/* This is the current call context object. While it is publicly available,
Use smalltalk.getThisContext() instead which will answer a safe copy of
the current context */
st.thisContext = undefined;
/* List of all reserved words in JavaScript. They may not be used as variables
in Smalltalk. */
// list of reserved JavaScript keywords as of
// http://es5.github.com/#x7.6.1.1
// and
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
'try', 'typeof', 'var', 'void', 'while', 'with',
// ES5: future use: http://es5.github.com/#x7.6.1.2
'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
// ES5: future use in strict mode
'implements', 'interface', 'let', 'package', 'private', 'protected',
'public', 'static', 'yield'];
var initialized = false;
/* Smalltalk classes */
var classes = [];
var wrappedClasses = [];
/* Method not implemented handlers */
var dnu = {
methods: [],
selectors: [],
get: function (string) {
var index = this.selectors.indexOf(string);
if(index !== -1) {
return this.methods[index];
}
this.selectors.push(string);
var selector = st.selector(string);
var method = {jsSelector: selector, fn: this.createHandler(selector)};
this.methods.push(method);
return method;
},
/* Dnu handler method */
createHandler: function (selector) {
return function () {
var args = Array.prototype.slice.call(arguments);
return messageNotUnderstood(this, selector, args);
};
}
};
/* The symbol table ensures symbol unicity */
var symbolTable = {};
st.symbolFor = function(string) {
if(symbolTable[string] === undefined) {
symbolTable[string] = new SmalltalkSymbol(string);
}
return symbolTable[string];
};
/* Unique ID number generator */
var oid = 0;
st.nextId = function() {
oid += 1;
return oid;
};
/* We hold all Packages in a separate Object */
st.packages = {};
/* Smalltalk package creation. To add a Package, use smalltalk.addPackage() */
function pkg(spec) {
var that = new SmalltalkPackage();
that.pkgName = spec.pkgName;
that.organization = new SmalltalkOrganizer();
that.properties = spec.properties || {};
return that;
}
/* Smalltalk class creation. A class is an instance of an automatically
created metaclass object. Newly created classes (not their metaclass)
should be added to the smalltalk object, see smalltalk.addClass().
Superclass linking is *not* handled here, see smalltalk.init() */
function klass(spec) {
spec = spec || {};
var meta = metaclass(spec);
var that = meta.instanceClass;
that.fn = spec.fn || function() {};
setupClass(that, spec);
that.className = spec.className;
that.wrapped = spec.wrapped || false;
meta.className = spec.className + ' class';
if(spec.superclass) {
that.superclass = spec.superclass;
meta.superclass = spec.superclass.klass;
}
return that;
}
function metaclass(spec) {
spec = spec || {};
var that = new SmalltalkMetaclass();
inherits(
that.fn = function() {},
spec.superclass ? spec.superclass.klass.fn : SmalltalkClass
);
that.instanceClass = new that.fn();
setupClass(that);
return that;
}
function setupClass(klass, spec) {
spec = spec || {};
klass.iVarNames = spec.iVarNames || [];
klass.pkg = spec.pkg;
Object.defineProperty(klass, "toString", {
value: function() { return 'Smalltalk ' + this.className; },
enumerable:false, configurable: true, writable: false
});
klass.organization = new SmalltalkOrganizer();
Object.defineProperty(klass, "methods", {
value: {},
enumerable: false, configurable: true, writable: true
});
wireKlass(klass);
}
/* Smalltalk method object. To add a method to a class,
use smalltalk.addMethod() */
st.method = function(spec) {
var that = new SmalltalkMethod();
that.selector = spec.selector;
that.jsSelector = spec.jsSelector;
that.args = spec.args || {};
that.category = spec.category;
that.source = spec.source;
that.messageSends = spec.messageSends || [];
that.referencedClasses = spec.referencedClasses || [];
that.fn = spec.fn;
return that;
};
/* Initialize a class in its class hierarchy. Handle both classes and
metaclasses. */
st.init = function(klass) {
st.initClass(klass);
if(klass.klass && !klass.meta) {
st.initClass(klass.klass);
}
};
st.initClass = function(klass) {
if(klass.wrapped) {
copySuperclass(klass);
}
else {
installSuperclass(klass);
}
if(klass === st.Object || klass.wrapped) {
installDnuHandlers(klass);
}
};
function wireKlass(klass) {
Object.defineProperty(klass.fn.prototype, "klass", {
value: klass,
enumerable: false, configurable: true, writable: true
});
}
function installSuperclass(klass) {
// only if the klass has not been initialized yet.
if(klass.fn.prototype._yourself) { return; }
if(klass.superclass && klass.superclass !== nil) {
inherits(klass.fn, klass.superclass.fn);
wireKlass(klass);
reinstallMethods(klass);
}
}
function copySuperclass(klass, superclass) {
for (superclass = superclass || klass.superclass;
superclass && superclass !== nil;
superclass = superclass.superclass) {
for (var keys = Object.keys(superclass.methods), i = 0; i < keys.length; i++) {
installMethodIfAbsent(superclass.methods[keys[i]], klass);
}
}
}
function installMethod(method, klass) {
Object.defineProperty(klass.fn.prototype, method.jsSelector, {
value: method.fn,
enumerable: false, configurable: true, writable: true
});
}
function installMethodIfAbsent(method, klass) {
if(!klass.fn.prototype[method.jsSelector]) {
installMethod(method, klass);
}
}
function reinstallMethods(klass) {
for(var keys = Object.keys(klass.methods), i=0; i<keys.length; i++) {
installMethod(klass.methods[keys[i]], klass);
}
}
function installDnuHandlers(klass) {
var m = dnu.methods;
for(var i=0; i<m.length; i++) {
installMethodIfAbsent(m[i], klass);
}
}
function installNewDnuHandler(newHandler) {
installMethodIfAbsent(newHandler, st.Object);
for(var i = 0; i < wrappedClasses.length; i++) {
installMethodIfAbsent(newHandler, wrappedClasses[i]);
}
}
/* Answer all registered Packages as Array */
// TODO: Remove this hack
st.packages.all = function() {
var packages = [];
for(var i in st.packages) {
if(!st.packages.hasOwnProperty(i) || typeof(st.packages[i]) === "function") continue;
packages.push(st.packages[i]);
}
return packages
};
/* Answer all registered Smalltalk classes */
//TODO: remove the function and make smalltalk.classes an array
st.classes = function() {
return classes;
};
st.wrappedClasses = function() {
return wrappedClasses;
};
/* Answer the direct subclasses of klass. */
st.subclasses = function(klass) {
var subclasses = [];
var classes = st.classes();
for(var i=0; i < classes.length; i++) {
var c = classes[i];
if(c.fn) {
//Classes
if(c.superclass === klass) {
subclasses.push(c);
}
c = c.klass;
//Metaclasses
if(c && c.superclass === klass) {
subclasses.push(c);
}
}
}
return subclasses;
};
/* Create a new class wrapping a JavaScript constructor, and add it to the
global smalltalk object. Package is lazily created if it does not exist with given name. */
st.wrapClassName = function(className, pkgName, fn, superclass, wrapped) {
if(wrapped !== false) {
wrapped = true;
}
var pkg = st.addPackage(pkgName);
st[className] = klass({
className: className,
superclass: superclass,
pkg: pkg,
fn: fn,
wrapped: wrapped
});
classes.addElement(st[className]);
if(wrapped) {wrappedClasses.addElement(st[className])}
pkg.organization.elements.addElement(st[className]);
};
/* Create an alias for an existing class */
st.alias = function(klass, alias) {
st[alias] = klass;
};
/* Add a package to the smalltalk.packages object, creating a new one if needed.
If pkgName is null or empty we return nil, which is an allowed package for a class.
If package already exists we still update the properties of it. */
st.addPackage = function(pkgName, properties) {
if(!pkgName) {return nil;}
if(!(st.packages[pkgName])) {
st.packages[pkgName] = pkg({
pkgName: pkgName,
properties: properties
});
} else {
if(properties) {
st.packages[pkgName].properties = properties;
}
}
return st.packages[pkgName];
};
/* Add a class to the smalltalk object, creating a new one if needed.
A Package is lazily created if it does not exist with given name. */
st.addClass = function(className, superclass, iVarNames, pkgName) {
var pkg = st.addPackage(pkgName);
if (superclass == nil) { superclass = null; }
if(st[className] && st[className].superclass == superclass) {
st[className].superclass = superclass;
st[className].iVarNames = iVarNames;
st[className].pkg = pkg || st[className].pkg;
} else {
if(st[className]) {
st.removeClass(st[className]);
}
st[className] = klass({
className: className,
superclass: superclass,
pkg: pkg,
iVarNames: iVarNames
});
}
classes.addElement(st[className]);
pkg.organization.elements.addElement(st[className]);
};
st.removeClass = function(klass) {
klass.pkg.organization.elements.removeElement(klass);
classes.removeElement(klass);
delete st[klass.className];
};
/* Add/remove a method to/from a class */
st.addMethod = function(jsSelector, method, klass) {
method.jsSelector = jsSelector;
installMethod(method, klass);
klass.methods[method.selector] = method;
method.methodClass = klass;
klass.organization.elements.addElement(method.category);
for(var i=0; i<method.messageSends.length; i++) {
var dnuHandler = dnu.get(method.messageSends[i]);
if(initialized) {
installNewDnuHandler(dnuHandler);
}
}
};
st.removeMethod = function(method) {
var protocol = method.category;
var klass = method.methodClass;
delete klass.fn.prototype[st.selector(method.selector)];
delete klass.methods[method.selector];
var selectors = Object.keys(klass.methods);
var shouldDeleteProtocol = true;
for(var i = 0, l = selectors.length; i<l; i++) {
if(klass.methods[selectors[i]].category === protocol) {
shouldDeleteProtocol = false;
break;
};
};
if(shouldDeleteProtocol) {
klass.organization.elements.removeElement(protocol)
};
};
/* Handles unhandled errors during message sends */
// simply send the message and handle #dnu:
st.send = function(receiver, selector, args, klass) {
var method;
if(receiver == null) {
receiver = nil;
}
method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
if(method) {
return method.apply(receiver, args);
} else {
return messageNotUnderstood(receiver, selector, args);
}
}
st.withContext = function(worker, setup) {
if(st.thisContext) {
st.thisContext.pc++;
return inContext(worker, setup);
} else {
try {return inContext(worker, setup)}
catch(error) {
// Reset the context stack in any case
st.thisContext = undefined;
if(error.smalltalkError) {
handleError(error);
return nil;
} else {
throw(error);
}
}
}
};
function inContext(worker, setup) {
var context = pushContext(setup);
var result = worker(context);
popContext(context);
return result;
}
/* Handles Smalltalk errors. Triggers the registered ErrorHandler
(See the Smalltalk class ErrorHandler and its subclasses */
function handleError(error) {
st.ErrorHandler._current()._handleError_(error);
}
/* Handles #dnu: *and* JavaScript method calls.
if the receiver has no klass, we consider it a JS object (outside of the
Amber system). Else assume that the receiver understands #doesNotUnderstand: */
function messageNotUnderstood(receiver, selector, args) {
/* Handles JS method calls. */
if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
return callJavaScriptMethod(receiver, selector, args);
}
/* Handles not understood messages. Also see the Amber counter-part
Object>>doesNotUnderstand: */
return receiver._doesNotUnderstand_(
st.Message._new()
._selector_(st.convertSelector(selector))
._arguments_(args)
);
}
/* Call a method of a JS object, or answer a property if it exists.
Else try wrapping a JSObjectProxy around the receiver.
If the object property is a function, then call it, except if it starts with
an uppercase character (we probably want to answer the function itself in this
case and send it #new from Amber).
Converts keyword-based selectors by using the first
keyword only, but keeping all message arguments.
Example:
"self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
function callJavaScriptMethod(receiver, selector, args) {
var jsSelector = selector._asJavaScriptSelector();
var jsProperty = receiver[jsSelector];
if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
return jsProperty.apply(receiver, args);
} else if(jsProperty !== undefined) {
if(args[0]) {
receiver[jsSelector] = args[0];
return nil;
} else {
return jsProperty;
}
}
return st.send(st.JSObjectProxy._on_(receiver), selector, args);
}
/* Handle thisContext pseudo variable */
st.getThisContext = function() {
if(st.thisContext) {
st.thisContext.init();
return st.thisContext;
} else {
return nil;
}
};
function pushContext(setup) {
return st.thisContext = new SmalltalkMethodContext(smalltalk.thisContext, setup);
}
function popContext(context) {
st.thisContext = context.homeContext;
}
/* Convert a Smalltalk selector into a JS selector */
st.selector = function(string) {
var selector = '_' + string;
selector = selector.replace(/:/g, '_');
selector = selector.replace(/[\&]/g, '_and');
selector = selector.replace(/[\|]/g, '_or');
selector = selector.replace(/[+]/g, '_plus');
selector = selector.replace(/-/g, '_minus');
selector = selector.replace(/[*]/g ,'_star');
selector = selector.replace(/[\/]/g ,'_slash');
selector = selector.replace(/[\\]/g ,'_backslash');
selector = selector.replace(/[\~]/g ,'_tild');
selector = selector.replace(/>/g ,'_gt');
selector = selector.replace(/</g ,'_lt');
selector = selector.replace(/=/g ,'_eq');
selector = selector.replace(/,/g ,'_comma');
selector = selector.replace(/[@]/g ,'_at');
return selector
};
/* Convert a string to a valid smalltalk selector.
if you modify the following functions, also change String>>asSelector
accordingly */
st.convertSelector = function(selector) {
if(selector.match(/__/)) {
return convertBinarySelector(selector);
} else {
return convertKeywordSelector(selector);
}
};
function convertKeywordSelector(selector) {
return selector.replace(/^_/, '').replace(/_/g, ':');
}
function convertBinarySelector(selector) {
return selector
.replace(/^_/, '')
.replace(/_and/g, '&')
.replace(/_or/g, '|')
.replace(/_plus/g, '+')
.replace(/_minus/g, '-')
.replace(/_star/g, '*')
.replace(/_slash/g, '/')
.replace(/_backslash/g, '\\')
.replace(/_tild/g, '~')
.replace(/_gt/g, '>')
.replace(/_lt/g, '<')
.replace(/_eq/g, '=')
.replace(/_comma/g, ',')
.replace(/_at/g, '@')
}
/* Converts a JavaScript object to valid Smalltalk Object */
st.readJSObject = function(js) {
var object = js;
var readObject = (js.constructor === Object);
var readArray = (js.constructor === Array);
if(readObject) {
object = st.Dictionary._new();
}
for(var i in js) {
if(readObject) {
object._at_put_(i, st.readJSObject(js[i]));
}
if(readArray) {
object[i] = st.readJSObject(js[i]);
}
}
return object;
};
/* Boolean assertion */
st.assert = function(shouldBeBoolean) {
if ((undefined !== shouldBeBoolean) && (shouldBeBoolean.klass === smalltalk.Boolean)) {
return shouldBeBoolean == true;
} else {
smalltalk.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
}
};
/* Smalltalk initialization. Called on page load */
st.initialize = function() {
if(initialized) { return; }
classes.forEach(function(klass) {
st.init(klass);
});
classes.forEach(function(klass) {
klass._initialize();
});
initialized = true;
};
}
inherits(Smalltalk, SmalltalkObject);
function SmalltalkMethodContext(home, setup) {
this.homeContext = home;
this.setup = setup || function() {};
this.pc = 0;
this.locals = {};
this.args = [];
}
inherits(SmalltalkMethodContext, SmalltalkObject);
SmalltalkMethodContext.prototype.fill = function(receiver, selector, args, locals, lookupClass) {
this.receiver = receiver;
this.selector = selector;
this.args = args || [];
this.locals = locals || {};
this.lookupClass = lookupClass;
};
SmalltalkMethodContext.prototype.fillBlock = function() {
this.receiver = null;
this.selector = null;
this.args = [];
this.locals = {};
this.lookupClass = null;
};
SmalltalkMethodContext.prototype.init = function() {
var home = this.homeContext;
if(home) {home = home.init()}
this.setup(this);
};
SmalltalkMethodContext.prototype.method = function() {
var method;
var lookup = this.lookupClass || this.receiver.klass;
while(!method && lookup) {
method = lookup.methods[smalltalk.convertSelector(this.selector)];
lookup = lookup.superclass
}
return method;
};
SmalltalkMethodContext.prototype.resume = function() {
//Brutally set the receiver as thisContext, then re-enter the function
smalltalk.thisContext = this;
return this.method.apply(receiver, temps);
};
/* Global Smalltalk objects. */
var nil = new SmalltalkNil();
var smalltalk = new Smalltalk();
if(this.jQuery) {
this.jQuery.allowJavaScriptCalls = true;
}
/*
* Answer the smalltalk representation of o.
* Used in message sends
*/
var _st = function(o) {
if(o == null) {return nil}
if(o.klass) {return o}
return smalltalk.JSObjectProxy._on_(o);
};
/***************************************** BOOTSTRAP ******************************************/
smalltalk.wrapClassName("Object", "Kernel-Objects", SmalltalkObject, undefined, false);
smalltalk.wrapClassName("Behavior", "Kernel-Classes", SmalltalkBehavior, smalltalk.Object, false);
smalltalk.wrapClassName("Metaclass", "Kernel-Classes", SmalltalkMetaclass, smalltalk.Behavior, false);
smalltalk.wrapClassName("Class", "Kernel-Classes", SmalltalkClass, smalltalk.Behavior, false);
smalltalk.Object.klass.superclass = smalltalk.Class;
smalltalk.wrapClassName("Smalltalk", "Kernel-Objects", Smalltalk, smalltalk.Object, false);
smalltalk.wrapClassName("Package", "Kernel-Objects", SmalltalkPackage, smalltalk.Object, false);
smalltalk.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, smalltalk.Object, false);
smalltalk.wrapClassName("Organizer", "Kernel-Objects", SmalltalkOrganizer, smalltalk.Object, false);
smalltalk.wrapClassName("Number", "Kernel", Number, smalltalk.Object);
smalltalk.wrapClassName("BlockClosure", "Kernel", Function, smalltalk.Object);
smalltalk.wrapClassName("Boolean", "Kernel", Boolean, smalltalk.Object);
smalltalk.wrapClassName("Date", "Kernel", Date, smalltalk.Object);
smalltalk.wrapClassName("UndefinedObject", "Kernel", SmalltalkNil, smalltalk.Object, false);
smalltalk.wrapClassName("Collection", "Kernel", null, smalltalk.Object, false);
smalltalk.wrapClassName("SequenceableCollection", "Kernel", null, smalltalk.Collection, false);
smalltalk.wrapClassName("CharacterArray", "Kernel", null, smalltalk.SequenceableCollection, false);
smalltalk.wrapClassName("String", "Kernel", String, smalltalk.CharacterArray);
smalltalk.wrapClassName("Symbol", "Kernel", SmalltalkSymbol, smalltalk.CharacterArray, false);
smalltalk.wrapClassName("Array", "Kernel", Array, smalltalk.SequenceableCollection);
smalltalk.wrapClassName("RegularExpression", "Kernel", RegExp, smalltalk.String);
smalltalk.wrapClassName("Error", "Kernel", Error, smalltalk.Object);
smalltalk.wrapClassName("MethodContext", "Kernel", SmalltalkMethodContext, smalltalk.Object, false);
/* Alias definitions */
smalltalk.alias(smalltalk.Array, "OrderedCollection");
smalltalk.alias(smalltalk.Date, "Time");
| fillBlock() takes the args and locals as arguments
| js/boot.js | fillBlock() takes the args and locals as arguments | <ide><path>s/boot.js
<ide> this.lookupClass = lookupClass;
<ide> };
<ide>
<del>SmalltalkMethodContext.prototype.fillBlock = function() {
<add>SmalltalkMethodContext.prototype.fillBlock = function(args, locals) {
<ide> this.receiver = null;
<ide> this.selector = null;
<del> this.args = [];
<del> this.locals = {};
<add> this.args = args || [];
<add> this.locals = locals || {};
<ide> this.lookupClass = null;
<ide> };
<ide> |
|
JavaScript | bsd-2-clause | 978b0036828d68816381b1060444c7fbbd6a30bd | 0 | mozilla/sweet.js,sweet-js/sweet-core,mozilla/sweet.js,sweet-js/sweet.js,sweet-js/sweet.js | #lang "../macros/stxcase.js";
/*
Copyright (C) 2012 Tim Disney <[email protected]>
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.
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 <COPYRIGHT HOLDER> 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 @ from "contracts.js"
(function (root, factory) {
if (typeof exports === 'object') {
// CommonJS
factory(exports,
require('underscore'),
require('./parser'),
require('./syntax'),
require('./scopedEval'),
require("./patterns"),
require('escodegen'),
require('vm'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports',
'underscore',
'parser',
'syntax',
'scopedEval',
'patterns',
'escodegen'], factory);
}
}(this, function(exports, _, parser, syn, se, patternModule, gen, vm) {
'use strict';
// escodegen still doesn't quite support AMD: https://github.com/Constellation/escodegen/issues/115
var codegen = typeof escodegen !== "undefined" ? escodegen : gen;
var assert = syn.assert;
var throwSyntaxError = syn.throwSyntaxError;
var throwSyntaxCaseError = syn.throwSyntaxCaseError;
var SyntaxCaseError = syn.SyntaxCaseError;
var unwrapSyntax = syn.unwrapSyntax;
macro (->) {
rule infix { $param:ident | { $body ... } } => {
function ($param) { $body ...}
}
rule infix { $param:ident | $body:expr } => {
function ($param) { return $body }
}
rule infix { ($param:ident (,) ...) | { $body ... } } => {
function ($param (,) ...) { $body ... }
}
rule infix { ($param:ident (,) ...) | $body:expr } => {
function ($param (,) ...) { return $body }
}
}
operator (|>) 1 left { $l, $r } => #{ $r($l) }
// used to export "private" methods for unit testing
exports._test = {};
function StringMap(o) {
this.__data = o || {};
}
StringMap.prototype = {
keys: function() {
return Object.keys(this.__data);
},
has: function(key) {
return Object.prototype.hasOwnProperty.call(this.__data, key);
},
get: function(key) {
return this.has(key) ? this.__data[key] : void 0;
},
set: function(key, value) {
this.__data[key] = value;
},
extend: function() {
var args = _.map(_.toArray(arguments), function(x) {
return x.__data;
});
_.extend.apply(_, [this.__data].concat(args));
return this;
}
}
var scopedEval = se.scopedEval;
var Rename = syn.Rename;
var Mark = syn.Mark;
var Def = syn.Def;
var Imported = syn.Imported;
var syntaxFromToken = syn.syntaxFromToken;
var joinSyntax = syn.joinSyntax;
var builtinMode = false;
var expandCount = 0;
var maxExpands;
var availableModules;
var push = Array.prototype.push;
function remdup(mark, mlist) {
if (mark === _.first(mlist)) {
return _.rest(mlist, 1);
}
return [mark].concat(mlist);
}
// (CSyntax) -> [...Num]
function marksof(ctx, stopName, originalName) {
while (ctx) {
if (ctx.constructor === Mark) {
return remdup(ctx.mark, marksof(ctx.context, stopName, originalName));
}
if(ctx.constructor === Def) {
ctx = ctx.context;
continue;
}
if (ctx.constructor === Rename) {
if(stopName === originalName + "$" + ctx.name) {
return [];
}
ctx = ctx.context;
continue;
}
if (ctx.constructor === Imported) {
ctx = ctx.context;
continue;
}
assert(false, "Unknown context type");
}
return [];
}
function resolve(stx, phase) {
assert(phase !== undefined, "must pass in phase");
return resolveCtx(stx.token.value, stx.context, [], [], {}, phase);
}
// This call memoizes intermediate results in the recursive invocation.
// The scope of the memo cache is the resolve() call, so that multiple
// resolve() calls don't walk all over each other, and memory used for
// the memoization can be garbage collected.
//
// The memoization addresses issue #232.
//
// It looks like the memoization uses only the context and doesn't look
// at originalName, stop_spine and stop_branch arguments. This is valid
// because whenever in every recursive call operates on a "deeper" or
// else a newly created context. Therefore the collection of
// [originalName, stop_spine, stop_branch] can all be associated with a
// unique context. This argument is easier to see in a recursive
// rewrite of the resolveCtx function than with the while loop
// optimization - https://gist.github.com/srikumarks/9847260 - where the
// recursive steps always operate on a different context.
//
// This might make it seem that the resolution results can be stored on
// the context object itself, but that would not work in general
// because multiple resolve() calls will walk over each other's cache
// results, which fails tests. So the memoization uses only a context's
// unique instance numbers as the memoization key and is local to each
// resolve() call.
//
// With this memoization, the time complexity of the resolveCtx call is
// no longer exponential for the cases in issue #232.
function resolveCtx(originalName, ctx, stop_spine, stop_branch, cache, phase) {
if (!ctx) { return originalName; }
var key = ctx.instNum;
return cache[key] || (cache[key] = resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache, phase));
}
// (Syntax) -> String
function resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache, phase) {
while (true) {
if (!ctx) { return originalName; }
if (ctx.constructor === Mark) {
ctx = ctx.context;
continue;
}
if (ctx.constructor === Def) {
if (stop_spine.indexOf(ctx.defctx) !== -1) {
ctx = ctx.context;
continue;
} else {
stop_branch = unionEl(stop_branch, ctx.defctx);
ctx = renames(ctx.defctx, ctx.context, originalName);
continue;
}
}
if (ctx.constructor === Rename) {
if (originalName === ctx.id.token.value) {
var idName = resolveCtx(ctx.id.token.value,
ctx.id.context,
stop_branch,
stop_branch,
cache,
0);
var subName = resolveCtx(originalName,
ctx.context,
unionEl(stop_spine, ctx.def),
stop_branch,
cache,
0);
if (idName === subName) {
var idMarks = marksof(ctx.id.context,
originalName + "$" + ctx.name,
originalName);
var subMarks = marksof(ctx.context,
originalName + "$" + ctx.name,
originalName);
if (arraysEqual(idMarks, subMarks)) {
return originalName + "$" + ctx.name;
}
}
}
ctx = ctx.context;
continue;
}
if (ctx.constructor === Imported) {
if (phase === ctx.phase) {
if (originalName === ctx.id.token.value) {
return originalName + "$" + ctx.name;
}
}
ctx = ctx.context;
continue;
}
assert(false, "Unknown context type");
}
}
function arraysEqual(a, b) {
if(a.length !== b.length) {
return false;
}
for(var i = 0; i < a.length; i++) {
if(a[i] !== b[i]) {
return false;
}
}
return true;
}
function renames(defctx, oldctx, originalName) {
var acc = oldctx;
for (var i = 0; i < defctx.length; i++) {
if (defctx[i].id.token.value === originalName) {
acc = new Rename(defctx[i].id, defctx[i].name, acc, defctx);
}
}
return acc;
}
function unionEl(arr, el) {
if (arr.indexOf(el) === -1) {
var res = arr.slice(0);
res.push(el);
return res;
}
return arr;
}
var nextFresh = 0;
// @ () -> Num
function fresh() { return nextFresh++; }
// wraps the array of syntax objects in the delimiters given by the second argument
// ([...CSyntax], CSyntax) -> [...CSyntax]
function wrapDelim(towrap, delimSyntax) {
assert(delimSyntax.token.type === parser.Token.Delimiter,
"expecting a delimiter token");
return syntaxFromToken({
type: parser.Token.Delimiter,
value: delimSyntax.token.value,
inner: towrap,
range: delimSyntax.token.range,
startLineNumber: delimSyntax.token.startLineNumber,
lineStart: delimSyntax.token.lineStart
}, delimSyntax);
}
// (CSyntax) -> [...CSyntax]
function getParamIdentifiers(argSyntax) {
if (argSyntax.token.type === parser.Token.Delimiter) {
return _.filter(argSyntax.token.inner, function(stx) { return stx.token.value !== ","});
} else if (argSyntax.token.type === parser.Token.Identifier) {
return [argSyntax];
} else {
assert(false, "expecting a delimiter or a single identifier for function parameters");
}
}
function inherit(parent, child, methods) {
var P = function(){};
P.prototype = parent.prototype;
child.prototype = new P();
child.prototype.constructor = child;
_.extend(child.prototype, methods);
}
macro cloned {
rule { $dest:ident <- $source:expr ;... } => {
var src = $source;
var keys = Object.keys(src);
var $dest = {};
for (var i = 0, len = keys.length, key; i < len; i++) {
key = keys[i];
$dest[key] = src[key];
}
}
}
macro to_str {
case { _ ($toks (,) ...) } => {
var toks = #{ $toks ... };
// We aren't using unwrapSyntax because it breaks since its defined
// within the outer scope! We need phases.
var str = toks.map(function(x) { return x.token.value }).join('');
return [makeValue(str, #{ here })];
}
}
macro class_method {
rule { $name:ident $args $body } => {
to_str($name): function $args $body
}
}
macro class_extend {
rule { $name $parent $methods } => {
inherit($parent, $name, $methods);
}
}
macro class_ctr {
rule { $name ($field ...) } => {
function $name($field (,) ...) {
$(this.$field = $field;) ...
}
}
}
macro class_create {
rule { $name ($arg (,) ...) } => {
$name.properties = [$(to_str($arg)) (,) ...];
$name.create = function($arg (,) ...) {
return new $name($arg (,) ...);
}
}
}
macro dataclass {
rule {
$name:ident ($field:ident (,) ...) extends $parent:ident {
$methods:class_method ...
} ;...
} => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
class_extend $name $parent {
to_str('is', $name): true,
$methods (,) ...
}
}
rule {
$name:ident ($field:ident (,) ...) {
$methods:class_method ...
} ;...
} => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
$name.prototype = {
to_str('is', $name): true,
$methods (,) ...
};
}
rule { $name:ident ($field (,) ...) extends $parent:ident ;... } => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
class_extend $name $parent {
to_str('is', $name): true
}
}
rule { $name:ident ($field (,) ...) ;... } => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
$name.prototype = {
to_str('is', $name): true
};
}
}
// @ let TemplateMap = {}
// @ let PatternMap = {}
// @ let TokenObject = {}
// @ let ContextObject = {}
// @ let SyntaxObject = {
// token: TokenObject,
// context: Null or ContextObject
// }
// @ let TermTreeObject = {}
// @ let ExpanderContext = {}
// {
// filename: Str,
// env: {},
// defscope: {},
// paramscope: {},
// templateMap: {},
// patternMap: {},
// mark: Num
// }
// @ let ExportTerm = {
// name: SyntaxObject
// }
// @ let ImportTerm = {
// names: SyntaxObject,
// from: SyntaxObject
// }
// @ let ModuleTerm = {
// name: SyntaxObject,
// lang: SyntaxObject,
// body: [...SyntaxObject] or [...TermTreeObject],
// imports: [...ImportTerm],
// exports: [...ExportTerm]
// }
// A TermTree is the core data structure for the macro expansion process.
// It acts as a semi-structured representation of the syntax.
dataclass TermTree() {
// Go back to the syntax object representation. Uses the
// ordered list of properties that each subclass sets to
// determine the order in which multiple children are
// destructed.
// ({stripCompileTerm: ?Boolean}) -> [...Syntax]
destruct(context, options) {
assert(context, "must pass in the context to destruct");
options = options || {};
var self = this;
if (options.stripCompileTerm && this.isCompileTimeTerm) {
return [];
}
if (options.stripModuleTerm && this.isModuleTerm) {
return [];
}
return _.reduce(this.constructor.properties, function(acc, prop) {
if (self[prop] && self[prop].isTermTree) {
push.apply(acc, self[prop].destruct(context, options));
return acc;
} else if (self[prop] && self[prop].token && self[prop].token.inner) {
cloned newtok <- self[prop].token;
var clone = syntaxFromToken(newtok, self[prop]);
clone.token.inner = _.reduce(clone.token.inner, function(acc, t) {
if (t && t.isTermTree) {
push.apply(acc, t.destruct(context, options));
return acc;
}
acc.push(t);
return acc;
}, []);
acc.push(clone);
return acc;
} else if (Array.isArray(self[prop])) {
var destArr = _.reduce(self[prop], function(acc, t) {
if (t && t.isTermTree) {
push.apply(acc, t.destruct(context, options));
return acc;
}
acc.push(t);
return acc;
}, []);
push.apply(acc, destArr);
return acc;
} else if (self[prop]) {
acc.push(self[prop]);
return acc;
} else {
return acc;
}
}, []);
}
addDefCtx(def) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.addDefCtx(def);
});
} else if (self[prop]) {
self[prop] = self[prop].addDefCtx(def);
}
});
return this;
}
rename(id, name, phase) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.rename(id, name, phase);
});
} else if (self[prop]) {
self[prop] = self[prop].rename(id, name, phase);
}
});
return this;
}
imported(id, name, phase) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.imported(id, name, phase);
});
} else if (self[prop]) {
self[prop] = self[prop].imported(id, name, phase);
}
});
return this;
}
}
dataclass EOF (eof) extends TermTree;
dataclass Keyword (keyword) extends TermTree;
dataclass Punc (punc) extends TermTree;
dataclass Delimiter (delim) extends TermTree;
dataclass ModuleTerm () extends TermTree;
dataclass Module (body) extends ModuleTerm;
dataclass Import (kw, names, fromkw, from) extends ModuleTerm;
dataclass ImportForMacros (names, from) extends ModuleTerm;
dataclass Export (kw, name) extends ModuleTerm;
dataclass CompileTimeTerm () extends TermTree;
dataclass LetMacro (name, body) extends CompileTimeTerm;
dataclass Macro (name, body) extends CompileTimeTerm;
dataclass AnonMacro (body) extends CompileTimeTerm;
dataclass OperatorDefinition (type, name, prec, assoc, body) extends CompileTimeTerm;
dataclass VariableDeclaration (ident, eq, init, comma) extends TermTree;
dataclass Statement () extends TermTree;
dataclass Empty () extends Statement;
dataclass CatchClause (keyword, params, body) extends Statement;
dataclass ForStatement (keyword, cond) extends Statement;
dataclass ReturnStatement (keyword, expr) extends Statement {
destruct(context, options) {
var expr = this.expr.destruct(context, options);
// need to adjust the line numbers to make sure that the expr
// starts on the same line as the return keyword. This might
// not be the case if an operator or infix macro perturbed the
// line numbers during expansion.
expr = adjustLineContext(expr, this.keyword.keyword);
return this.keyword.destruct(context, options).concat(expr);
}
}
dataclass Expr () extends Statement;
dataclass UnaryOp (op, expr) extends Expr;
dataclass PostfixOp (expr, op) extends Expr;
dataclass BinOp (left, op, right) extends Expr;
dataclass AssignmentExpression (left, op, right) extends Expr;
dataclass ConditionalExpression (cond, question, tru, colon, fls) extends Expr;
dataclass NamedFun (keyword, star, name, params, body) extends Expr;
dataclass AnonFun (keyword, star, params, body) extends Expr;
dataclass ArrowFun (params, arrow, body) extends Expr;
dataclass ObjDotGet (left, dot, right) extends Expr;
dataclass ObjGet (left, right) extends Expr;
dataclass Template (template) extends Expr;
dataclass Call (fun, args) extends Expr;
dataclass QuoteSyntax (stx) extends Expr {
destruct(context, options) {
var tempId = fresh();
context.templateMap.set(tempId, this.stx.token.inner);
return [syn.makeIdent("getTemplate", this.stx),
syn.makeDelim("()", [
syn.makeValue(tempId, this.stx)
], this.stx)];
}
}
dataclass PrimaryExpression () extends Expr;
dataclass ThisExpression (keyword) extends PrimaryExpression;
dataclass Lit (lit) extends PrimaryExpression;
dataclass Block (body) extends PrimaryExpression;
dataclass ArrayLiteral (array) extends PrimaryExpression;
dataclass Id (id) extends PrimaryExpression;
dataclass Partial () extends TermTree;
dataclass PartialOperation (stx, left) extends Partial;
dataclass PartialExpression (stx, left, combine) extends Partial;
dataclass BindingStatement(keyword, decls) extends Statement {
destruct(context, options) {
return this.keyword
.destruct(context, options)
.concat(_.reduce(this.decls, function(acc, decl) {
push.apply(acc, decl.destruct(context, options));
return acc;
}, []));
}
}
dataclass VariableStatement (keyword, decls) extends BindingStatement;
dataclass LetStatement (keyword, decls) extends BindingStatement;
dataclass ConstStatement (keyword, decls) extends BindingStatement;
dataclass ParenExpression(args, delim, commas) extends PrimaryExpression {
destruct(context, options) {
var commas = this.commas.slice();
cloned newtok <- this.delim.token;
var delim = syntaxFromToken(newtok, this.delim);
delim.token.inner = _.reduce(this.args, function(acc, term) {
assert(term && term.isTermTree,
"expecting term trees in destruct of ParenExpression");
push.apply(acc, term.destruct(context, options));
// add all commas except for the last one
if (commas.length > 0) {
acc.push(commas.shift());
}
return acc;
}, []);
return Delimiter.create(delim).destruct(context, options);
}
}
function stxIsUnaryOp(stx) {
var staticOperators = ["+", "-", "~", "!",
"delete", "void", "typeof", "yield", "new",
"++", "--"];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function stxIsBinOp(stx) {
var staticOperators = ["+", "-", "*", "/", "%", "||", "&&", "|", "&", "^",
"==", "!=", "===", "!==",
"<", ">", "<=", ">=", "in", "instanceof",
"<<", ">>", ">>>"];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function getUnaryOpPrec(op) {
var operatorPrecedence = {
"new": 16,
"++": 15,
"--": 15,
"!": 14,
"~": 14,
"+": 14,
"-": 14,
"typeof": 14,
"void": 14,
"delete": 14,
"yield": 2
}
return operatorPrecedence[op];
}
function getBinaryOpPrec(op) {
var operatorPrecedence = {
"*": 13,
"/": 13,
"%": 13,
"+": 12,
"-": 12,
">>": 11,
"<<": 11,
">>>": 11,
"<": 10,
"<=": 10,
">": 10,
">=": 10,
"in": 10,
"instanceof": 10,
"==": 9,
"!=": 9,
"===": 9,
"!==": 9,
"&": 8,
"^": 7,
"|": 6,
"&&": 5,
"||":4
}
return operatorPrecedence[op];
}
function getBinaryOpAssoc(op) {
var operatorAssoc = {
"*": "left",
"/": "left",
"%": "left",
"+": "left",
"-": "left",
">>": "left",
"<<": "left",
">>>": "left",
"<": "left",
"<=": "left",
">": "left",
">=": "left",
"in": "left",
"instanceof": "left",
"==": "left",
"!=": "left",
"===": "left",
"!==": "left",
"&": "left",
"^": "left",
"|": "left",
"&&": "left",
"||": "left"
}
return operatorAssoc[op];
}
function stxIsAssignOp(stx) {
var staticOperators = ["=", "+=", "-=", "*=", "/=", "%=",
"<<=", ">>=", ">>>=",
"|=", "^=", "&="];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function enforestVarStatement(stx, context, varStx) {
var decls = [];
var rest = stx;
var rhs;
if (!rest.length) {
throwSyntaxError("enforest", "Unexpected end of input", varStx);
}
if(expandCount >= maxExpands) {
return null;
}
while (rest.length) {
if (rest[0].token.type === parser.Token.Identifier) {
if (rest[1] && rest[1].token.type === parser.Token.Punctuator &&
rest[1].token.value === "=") {
rhs = get_expression(rest.slice(2), context);
if (rhs.result == null) {
throwSyntaxError("enforest", "Unexpected token", rhs.rest[0]);
}
if (rhs.rest[0] && rhs.rest[0].token.type === parser.Token.Punctuator &&
rhs.rest[0].token.value === ",") {
decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, rhs.rest[0]));
rest = rhs.rest.slice(1);
continue;
} else {
decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, null));
rest = rhs.rest;
break;
}
} else if (rest[1] && rest[1].token.type === parser.Token.Punctuator &&
rest[1].token.value === ",") {
decls.push(VariableDeclaration.create(rest[0], null, null, rest[1]));
rest = rest.slice(2);
} else {
decls.push(VariableDeclaration.create(rest[0], null, null, null));
rest = rest.slice(1);
break;
}
} else {
throwSyntaxError("enforest", "Unexpected token", rest[0]);
}
}
return {
result: decls,
rest: rest
}
}
function enforestAssignment(stx, context, left, prevStx, prevTerms) {
var op = stx[0];
var rightStx = stx.slice(1);
var opTerm = Punc.create(stx[0]);
var opPrevStx = tagWithTerm(opTerm, [stx[0]])
.concat(tagWithTerm(left, left.destruct(context).reverse()),
prevStx);
var opPrevTerms = [opTerm, left].concat(prevTerms);
var opRes = enforest(rightStx, context, opPrevStx, opPrevTerms);
if (opRes.result) {
// Lookbehind was matched, so it may not even be a binop anymore.
if (opRes.prevTerms.length < opPrevTerms.length) {
return opRes;
}
var right = opRes.result;
// only a binop if the right is a real expression
// so 2+2++ will only match 2+2
if (right.isExpr) {
var term = AssignmentExpression.create(left, op, right);
return {
result: term,
rest: opRes.rest,
prevStx: prevStx,
prevTerms: prevTerms
};
}
} else {
return opRes;
}
}
function enforestParenExpression(parens, context) {
var argRes, enforestedArgs = [], commas = [];
var innerTokens = parens.token.inner;
while (innerTokens.length > 0) {
argRes = enforest(innerTokens, context);
if (!argRes.result || !argRes.result.isExpr) {
return null;
}
enforestedArgs.push(argRes.result);
innerTokens = argRes.rest;
if (innerTokens[0] && innerTokens[0].token.value === ",") {
// record the comma for later
commas.push(innerTokens[0]);
// but dump it for the next loop turn
innerTokens = innerTokens.slice(1);
} else {
// either there are no more tokens or
// they aren't a comma, either way we
// are done with the loop
break;
}
}
return innerTokens.length ? null : ParenExpression.create(enforestedArgs, parens, commas);
}
function adjustLineContext(stx, original, current) {
// short circuit when the array is empty;
if (stx.length === 0) {
return stx;
}
current = current || {
lastLineNumber: stx[0].token.lineNumber || stx[0].token.startLineNumber,
lineNumber: original.token.lineNumber
};
return _.map(stx, function(stx) {
if (stx.token.type === parser.Token.Delimiter) {
// handle tokens with missing line info
stx.token.startLineNumber = typeof stx.token.startLineNumber == 'undefined'
? original.token.lineNumber
: stx.token.startLineNumber
stx.token.endLineNumber = typeof stx.token.endLineNumber == 'undefined'
? original.token.lineNumber
: stx.token.endLineNumber
stx.token.startLineStart = typeof stx.token.startLineStart == 'undefined'
? original.token.lineStart
: stx.token.startLineStart
stx.token.endLineStart = typeof stx.token.endLineStart == 'undefined'
? original.token.lineStart
: stx.token.endLineStart
stx.token.startRange = typeof stx.token.startRange == 'undefined'
? original.token.range
: stx.token.startRange
stx.token.endRange = typeof stx.token.endRange == 'undefined'
? original.token.range
: stx.token.endRange
stx.token.sm_startLineNumber = typeof stx.token.sm_startLineNumber == 'undefined'
? stx.token.startLineNumber
: stx.token.sm_startLineNumber;
stx.token.sm_endLineNumber = typeof stx.token.sm_endLineNumber == 'undefined'
? stx.token.endLineNumber
: stx.token.sm_endLineNumber;
stx.token.sm_startLineStart = typeof stx.token.sm_startLineStart == 'undefined'
? stx.token.startLineStart
: stx.token.sm_startLineStart;
stx.token.sm_endLineStart = typeof stx.token.sm_endLineStart == 'undefined'
? stx.token.endLineStart
: stx.token.sm_endLineStart;
stx.token.sm_startRange = typeof stx.token.sm_startRange == 'undefined'
? stx.token.startRange
: stx.token.sm_startRange;
stx.token.sm_endRange = typeof stx.token.sm_endRange == 'undefined'
? stx.token.endRange
: stx.token.sm_endRange;
if (stx.token.startLineNumber !== current.lineNumber) {
if (stx.token.startLineNumber !== current.lastLineNumber) {
current.lineNumber++;
current.lastLineNumber = stx.token.startLineNumber;
stx.token.startLineNumber = current.lineNumber;
} else {
current.lastLineNumber = stx.token.startLineNumber;
stx.token.startLineNumber = current.lineNumber;
}
}
return stx;
}
// handle tokens with missing line info
stx.token.lineNumber = typeof stx.token.lineNumber == 'undefined'
? original.token.lineNumber
: stx.token.lineNumber;
stx.token.lineStart = typeof stx.token.lineStart == 'undefined'
? original.token.lineStart
: stx.token.lineStart;
stx.token.range = typeof stx.token.range == 'undefined'
? original.token.range
: stx.token.range;
// Only set the sourcemap line info once. Necessary because a single
// syntax object can go through expansion multiple times. If at some point
// we want to write an expansion stepper this might be a good place to store
// intermediate expansion line info (ie push to a stack instead of
// just write once).
stx.token.sm_lineNumber = typeof stx.token.sm_lineNumber == 'undefined'
? stx.token.lineNumber
: stx.token.sm_lineNumber;
stx.token.sm_lineStart = typeof stx.token.sm_lineStart == 'undefined'
? stx.token.lineStart
: stx.token.sm_lineStart;
stx.token.sm_range = typeof stx.token.sm_range == 'undefined'
? stx.token.range.slice()
: stx.token.sm_range;
// move the line info to line up with the macro name
// (line info starting from the macro name)
if (stx.token.lineNumber !== current.lineNumber) {
if (stx.token.lineNumber !== current.lastLineNumber) {
current.lineNumber++;
current.lastLineNumber = stx.token.lineNumber;
stx.token.lineNumber = current.lineNumber;
} else {
current.lastLineNumber = stx.token.lineNumber;
stx.token.lineNumber = current.lineNumber;
}
}
return stx;
});
}
function getName(head, rest) {
var idx = 0;
var curr = head;
var next = rest[idx];
var name = [head];
while (true) {
if (next &&
(next.token.type === parser.Token.Punctuator ||
next.token.type === parser.Token.Identifier ||
next.token.type === parser.Token.Keyword) &&
(toksAdjacent(curr, next))) {
name.push(next);
curr = next;
next = rest[++idx];
} else {
return name;
}
}
}
function getValueInEnv(head, rest, context, phase) {
if (!(head.token.type === parser.Token.Identifier ||
head.token.type === parser.Token.Keyword ||
head.token.type === parser.Token.Punctuator)) {
return null;
}
var name = getName(head, rest);
// simple case, don't need to create a new syntax object
if (name.length === 1) {
if (context.env.names.get(unwrapSyntax(name[0]))) {
var resolvedName = resolve(name[0], phase);
if (context.env.has(resolvedName)) {
return context.env.get(resolvedName);
}
}
return null;
} else {
while (name.length > 0) {
var nameStr = name.map(unwrapSyntax).join("");
if (context.env.names.get(nameStr)) {
var nameStx = syn.makeIdent(nameStr, name[0]);
var resolvedName = resolve(nameStx, phase);
if (context.env.has(resolvedName)) {
return context.env.get(resolvedName);
}
}
name.pop();
}
return null;
}
}
function nameInEnv(head, rest, context, phase) {
return getValueInEnv(head, rest, context, phase) !== null;
}
// This should only be used on things that can't be rebound except by
// macros (puncs, keywords).
function resolveFast(stx, env, phase) {
var name = unwrapSyntax(stx);
return env.names.get(name) ? resolve(stx, phase) : name;
}
function expandMacro(stx, context, opCtx, opType, macroObj) {
// pull the macro transformer out the environment
var head = stx[0];
var rest = stx.slice(1);
macroObj = macroObj || getValueInEnv(head, rest, context, context.phase);
var stxArg = rest.slice(macroObj.fullName.length - 1);
var transformer;
if (opType != null) {
assert(opType === "binary" || opType === "unary", "operator type should be either unary or binary: " + opType);
transformer = macroObj[opType].fn;
} else {
transformer = macroObj.fn;
}
assert(typeof transformer === "function", "Macro transformer not bound for: "
+ head.token.value);
// create a new mark to be used for the input to
// the macro
var newMark = fresh();
var transformerContext = makeExpanderContext(_.defaults({mark: newMark}, context));
// apply the transformer
var rt;
try {
rt = transformer([head].concat(stxArg),
transformerContext,
opCtx.prevStx,
opCtx.prevTerms);
} catch (e) {
if (e instanceof SyntaxCaseError) {
// add a nicer error for syntax case
var nameStr = macroObj.fullName.map(function(stx) {
return stx.token.value;
}).join("");
if (opType != null) {
var argumentString = "`" + stxArg.slice(0, 5).map(function(stx) {
return stx.token.value;
}).join(" ") + "...`";
throwSyntaxError("operator", "Operator `" + nameStr +
"` could not be matched with " +
argumentString,
head);
} else {
var argumentString = "`" + stxArg.slice(0, 5).map(function(stx) {
return stx.token.value;
}).join(" ") + "...`";
throwSyntaxError("macro", "Macro `" + nameStr +
"` could not be matched with " +
argumentString,
head);
}
}
else {
// just rethrow it
throw e;
}
}
if (!builtinMode && !macroObj.builtin) {
expandCount++;
}
if(!Array.isArray(rt.result)) {
throwSyntaxError("enforest", "Macro must return a syntax array", stx[0]);
}
if(rt.result.length > 0) {
var adjustedResult = adjustLineContext(rt.result, head);
if (stx[0].token.leadingComments) {
if (adjustedResult[0].token.leadingComments) {
adjustedResult[0].token.leadingComments = adjustedResult[0].token.leadingComments.concat(head.token.leadingComments);
} else {
adjustedResult[0].token.leadingComments = head.token.leadingComments;
}
}
rt.result = adjustedResult;
}
return rt;
}
function comparePrec(left, right, assoc) {
if (assoc === "left") {
return left <= right;
}
return left < right;
}
// @ (SyntaxObject, SyntaxObject) -> Bool
function toksAdjacent(a, b) {
var arange = a.token.sm_range || a.token.range || a.token.endRange;
var brange = b.token.sm_range || b.token.range || b.token.endRange;
return arange && brange && arange[1] === brange[0];
}
// @ (SyntaxObject, SyntaxObject) -> Bool
function syntaxInnerValuesEq(synA, synB) {
var a = synA.token.inner, b = synB.token.inner;
return a.length === b.length &&
_.zip(a, b) |> ziped -> _.all(ziped, pair -> {
return unwrapSyntax(pair[0]) === unwrapSyntax(pair[1]);
});
}
// enforest the tokens, returns an object with the `result` TermTree and
// the uninterpreted `rest` of the syntax
// @ ([...SyntaxObject], ExpanderContext) -> {
// result: Null or TermTreeObject,
// rest: [...SyntaxObject]
// }
function enforest(toks, context, prevStx, prevTerms) {
assert(toks.length > 0, "enforest assumes there are tokens to work with");
prevStx = prevStx || [];
prevTerms = prevTerms || [];
if(expandCount >= maxExpands) {
return { result: null,
rest: toks };
}
function step(head, rest, opCtx) {
var innerTokens;
assert(Array.isArray(rest), "result must at least be an empty array");
if (head.isTermTree) {
var isCustomOp = false;
var uopMacroObj;
var uopSyntax;
if (head.isPunc || head.isKeyword || head.isId) {
if (head.isPunc) {
uopSyntax = head.punc;
} else if (head.isKeyword) {
uopSyntax = head.keyword;
} else if (head.isId) {
uopSyntax = head.id;
}
uopMacroObj = getValueInEnv(uopSyntax, rest, context, context.phase);
isCustomOp = uopMacroObj && uopMacroObj.isOp;
}
// look up once (we want to check multiple properties on bopMacroObj
// without repeatedly calling getValueInEnv)
var bopMacroObj;
if (rest[0] && rest[1]) {
bopMacroObj = getValueInEnv(rest[0], rest.slice(1), context, context.phase);
}
// unary operator
if ((isCustomOp && uopMacroObj.unary) || (uopSyntax && stxIsUnaryOp(uopSyntax))) {
var uopPrec;
if (isCustomOp && uopMacroObj.unary) {
uopPrec = uopMacroObj.unary.prec;
} else {
uopPrec = getUnaryOpPrec(unwrapSyntax(uopSyntax));
}
var opRest = rest;
var uopMacroName;
if (uopMacroObj) {
uopMacroName = [uopSyntax].concat(rest.slice(0, uopMacroObj.fullName.length - 1));
opRest = rest.slice(uopMacroObj.fullName.length - 1);
}
var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var unopTerm = PartialOperation.create(head, leftLeft);
var unopPrevStx = tagWithTerm(unopTerm, head.destruct(context).reverse()).concat(opCtx.prevStx);
var unopPrevTerms = [unopTerm].concat(opCtx.prevTerms);
var unopOpCtx = _.extend({}, opCtx, {
combine: function(t) {
if (t.isExpr) {
if (isCustomOp && uopMacroObj.unary) {
var rt = expandMacro(uopMacroName.concat(t.destruct(context)), context, opCtx, "unary");
var newt = get_expression(rt.result, context);
assert(newt.rest.length === 0, "should never have left over syntax");
return opCtx.combine(newt.result);
}
return opCtx.combine(UnaryOp.create(uopSyntax, t));
} else {
// not actually an expression so don't create
// a UnaryOp term just return with the punctuator
return opCtx.combine(head);
}
},
prec: uopPrec,
prevStx: unopPrevStx,
prevTerms: unopPrevTerms,
op: unopTerm
});
return step(opRest[0], opRest.slice(1), unopOpCtx);
// BinOp
} else if (head.isExpr &&
(rest[0] && rest[1] &&
((stxIsBinOp(rest[0]) && !bopMacroObj) ||
(bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary)))) {
var opRes;
var op = rest[0];
var left = head;
var rightStx = rest.slice(1);
var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var leftTerm = PartialExpression.create(head.destruct(context), leftLeft, function() {
return step(head, [], opCtx);
});
var opTerm = PartialOperation.create(op, leftTerm);
var opPrevStx = tagWithTerm(opTerm, [rest[0]])
.concat(tagWithTerm(leftTerm, head.destruct(context)).reverse(),
opCtx.prevStx);
var opPrevTerms = [opTerm, leftTerm].concat(opCtx.prevTerms);
var isCustomOp = bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary;
var bopPrec;
var bopAssoc;
if (isCustomOp && bopMacroObj.binary) {
bopPrec = bopMacroObj.binary.prec;
bopAssoc = bopMacroObj.binary.assoc;
} else {
bopPrec = getBinaryOpPrec(unwrapSyntax(op));
bopAssoc = getBinaryOpAssoc(unwrapSyntax(op));
}
assert(bopPrec !== undefined, "expecting a precedence for operator: " + op);
var newStack;
if (comparePrec(bopPrec, opCtx.prec, bopAssoc)) {
var bopCtx = opCtx;
var combResult = opCtx.combine(head);
if (opCtx.stack.length > 0) {
return step(combResult.term, rest, opCtx.stack[0]);
}
left = combResult.term;
newStack = opCtx.stack;
opPrevStx = combResult.prevStx;
opPrevTerms = combResult.prevTerms;
} else {
newStack = [opCtx].concat(opCtx.stack);
}
assert(opCtx.combine !== undefined,
"expecting a combine function");
var opRightStx = rightStx;
var bopMacroName;
if (isCustomOp) {
bopMacroName = rest.slice(0, bopMacroObj.fullName.length);
opRightStx = rightStx.slice(bopMacroObj.fullName.length - 1);
}
var bopOpCtx = _.extend({}, opCtx, {
combine: function(right) {
if (right.isExpr) {
if (isCustomOp && bopMacroObj.binary) {
var leftStx = left.destruct(context);
var rightStx = right.destruct(context);
var rt = expandMacro(bopMacroName.concat(syn.makeDelim("()", leftStx, leftStx[0]),
syn.makeDelim("()", rightStx, rightStx[0])),
context, opCtx, "binary");
var newt = get_expression(rt.result, context);
assert(newt.rest.length === 0, "should never have left over syntax");
return {
term: newt.result,
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
}
return {
term: BinOp.create(left, op, right),
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
} else {
return {
term: head,
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
}
},
prec: bopPrec,
op: opTerm,
stack: newStack,
prevStx: opPrevStx,
prevTerms: opPrevTerms,
});
return step(opRightStx[0], opRightStx.slice(1), bopOpCtx);
// Call
} else if (head.isExpr && (rest[0] &&
rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()")) {
var parenRes = enforestParenExpression(rest[0], context);
if (parenRes) {
return step(Call.create(head, parenRes),
rest.slice(1),
opCtx);
}
// Conditional ( x ? true : false)
} else if (head.isExpr &&
(rest[0] && resolveFast(rest[0], context.env, context.phase) === "?")) {
var question = rest[0];
var condRes = enforest(rest.slice(1), context);
if (condRes.result) {
var truExpr = condRes.result;
var condRight = condRes.rest;
if (truExpr.isExpr &&
condRight[0] && resolveFast(condRight[0], context.env, context.phase) === ":") {
var colon = condRight[0];
var flsRes = enforest(condRight.slice(1), context);
var flsExpr = flsRes.result;
if (flsExpr.isExpr) {
// operators are combined before the ternary
if (opCtx.prec >= 4) { // ternary is like a operator with prec 4
var headResult = opCtx.combine(head);
var condTerm = ConditionalExpression.create(headResult.term,
question,
truExpr,
colon,
flsExpr);
if (opCtx.stack.length > 0) {
return step(condTerm,
flsRes.rest,
opCtx.stack[0]);
} else {
return {
result: condTerm,
rest: flsRes.rest,
prevStx: headResult.prevStx,
prevTerms: headResult.prevTerms
};
}
} else {
var condTerm = ConditionalExpression.create(head,
question,
truExpr,
colon,
flsExpr);
return step(condTerm,
flsRes.rest,
opCtx);
}
}
}
}
// Arrow functions with expression bodies
} else if (head.isDelimiter &&
head.delim.token.value === "()" &&
rest[0] &&
rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>") {
var arrowRes = enforest(rest.slice(1), context);
if (arrowRes.result && arrowRes.result.isExpr) {
return step(ArrowFun.create(head.delim,
rest[0],
arrowRes.result.destruct(context)),
arrowRes.rest,
opCtx);
} else {
throwSyntaxError("enforest",
"Body of arrow function must be an expression",
rest.slice(1));
}
// Arrow functions with expression bodies
} else if (head.isId &&
rest[0] &&
rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>") {
var res = enforest(rest.slice(1), context);
if (res.result && res.result.isExpr) {
return step(ArrowFun.create(head.id,
rest[0],
res.result.destruct(context)),
res.rest,
opCtx);
} else {
throwSyntaxError("enforest",
"Body of arrow function must be an expression",
rest.slice(1));
}
// ParenExpr
} else if (head.isDelimiter &&
head.delim.token.value === "()") {
// empty parens are acceptable but enforest
// doesn't accept empty arrays so short
// circuit here
if (head.delim.token.inner.length === 0) {
return step(ParenExpression.create([Empty.create()], head.delim, []),
rest,
opCtx);
} else {
var parenRes = enforestParenExpression(head.delim, context);
if (parenRes) {
return step(parenRes, rest, opCtx);
}
}
// AssignmentExpression
} else if (head.isExpr &&
((head.isId ||
head.isObjGet ||
head.isObjDotGet ||
head.isThisExpression) &&
rest[0] && rest[1] && !bopMacroObj && stxIsAssignOp(rest[0]))) {
var opRes = enforestAssignment(rest, context, head, prevStx, prevTerms);
if(opRes && opRes.result) {
return step(opRes.result, opRes.rest, _.extend({}, opCtx, {
prevStx: opRes.prevStx,
prevTerms: opRes.prevTerms
}));
}
// Postfix
} else if(head.isExpr &&
(rest[0] && (unwrapSyntax(rest[0]) === "++" ||
unwrapSyntax(rest[0]) === "--"))) {
// Check if the operator is a macro first.
if (context.env.has(resolveFast(rest[0], context.env, context.phase))) {
var headStx = tagWithTerm(head, head.destruct(context).reverse());
var opPrevStx = headStx.concat(prevStx);
var opPrevTerms = [head].concat(prevTerms);
var opRes = enforest(rest, context, opPrevStx, opPrevTerms);
if (opRes.prevTerms.length < opPrevTerms.length) {
return opRes;
} else if(opRes.result) {
return step(head,
opRes.result.destruct(context).concat(opRes.rest),
opCtx);
}
}
return step(PostfixOp.create(head, rest[0]),
rest.slice(1),
opCtx);
// ObjectGet (computed)
} else if(head.isExpr &&
(rest[0] && rest[0].token.value === "[]")) {
return step(ObjGet.create(head, Delimiter.create(rest[0])),
rest.slice(1),
opCtx);
// ObjectGet
} else if (head.isExpr &&
(rest[0] && unwrapSyntax(rest[0]) === "." &&
!context.env.has(resolveFast(rest[0], context.env, context.phase)) &&
rest[1] &&
(rest[1].token.type === parser.Token.Identifier ||
rest[1].token.type === parser.Token.Keyword))) {
// Check if the identifier is a macro first.
if (context.env.has(resolveFast(rest[1], context.env, context.phase))) {
var headStx = tagWithTerm(head, head.destruct(context).reverse());
var dotTerm = Punc.create(rest[0]);
var dotTerms = [dotTerm].concat(head, prevTerms);
var dotStx = tagWithTerm(dotTerm, [rest[0]]).concat(headStx, prevStx);
var dotRes = enforest(rest.slice(1), context, dotStx, dotTerms);
if (dotRes.prevTerms.length < dotTerms.length) {
return dotRes;
} else if(dotRes.result) {
return step(head,
[rest[0]].concat(dotRes.result.destruct(context), dotRes.rest),
opCtx);
}
}
return step(ObjDotGet.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// ArrayLiteral
} else if (head.isDelimiter &&
head.delim.token.value === "[]") {
return step(ArrayLiteral.create(head), rest, opCtx);
// Block
} else if (head.isDelimiter &&
head.delim.token.value === "{}") {
return step(Block.create(head), rest, opCtx);
// quote syntax
} else if (head.isId &&
unwrapSyntax(head.id) === "#quoteSyntax" &&
rest[0] && rest[0].token.value === "{}") {
return step(QuoteSyntax.create(rest[0]), rest.slice(1), opCtx);
// return statement
} else if (head.isKeyword && unwrapSyntax(head.keyword) === "return") {
if (rest[0] && rest[0].token.lineNumber === head.keyword.token.lineNumber) {
var returnPrevStx = tagWithTerm(head,
head.destruct(context)).concat(opCtx.prevStx);
var returnPrevTerms = [head].concat(opCtx.prevTerms);
var returnExpr = enforest(rest, context, returnPrevStx, returnPrevTerms);
if (returnExpr.prevTerms.length < opCtx.prevTerms.length) {
return returnExpr;
}
if (returnExpr.result.isExpr) {
return step(ReturnStatement.create(head, returnExpr.result),
returnExpr.rest,
opCtx);
}
} else {
return step(ReturnStatement.create(head, Empty.create()),
rest,
opCtx);
}
// let statements
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "let") {
var nameTokens = [];
if (rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()") {
nameTokens = rest[0].token.inner;
} else {
nameTokens.push(rest[0]);
}
// Let macro
if (rest[1] && rest[1].token.value === "=" &&
rest[2] && rest[2].token.value === "macro") {
var mac = enforest(rest.slice(2), context);
if(mac.result) {
if (!mac.result.isAnonMacro) {
throwSyntaxError("enforest", "expecting an anonymous macro definition in syntax let binding", rest.slice(2));
}
return step(LetMacro.create(nameTokens, mac.result.body),
mac.rest,
opCtx);
}
// Let statement
} else {
var lsRes = enforestVarStatement(rest, context, head.keyword);
if (lsRes && lsRes.result) {
return step(LetStatement.create(head, lsRes.result),
lsRes.rest,
opCtx);
}
}
// VariableStatement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "var" && rest[0]) {
var vsRes = enforestVarStatement(rest, context, head.keyword);
if (vsRes && vsRes.result) {
return step(VariableStatement.create(head, vsRes.result),
vsRes.rest,
opCtx);
}
// Const Statement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "const" && rest[0]) {
var csRes = enforestVarStatement(rest, context, head.keyword);
if (csRes && csRes.result) {
return step(ConstStatement.create(head, csRes.result),
csRes.rest,
opCtx);
}
// for statement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "for" &&
rest[0] && rest[0].token.value === "()") {
return step(ForStatement.create(head.keyword, rest[0]),
rest.slice(1),
opCtx);
}
} else {
assert(head && head.token, "assuming head is a syntax object");
var macroObj = expandCount < maxExpands && getValueInEnv(head, rest, context, context.phase);
// macro invocation
if (macroObj && typeof macroObj.fn === "function" && !macroObj.isOp) {
var rt = expandMacro([head].concat(rest), context, opCtx, null, macroObj);
var newOpCtx = opCtx;
if (rt.prevTerms && rt.prevTerms.length < opCtx.prevTerms.length) {
newOpCtx = rewindOpCtx(opCtx, rt);
}
if (rt.result.length > 0) {
return step(rt.result[0],
rt.result.slice(1).concat(rt.rest),
newOpCtx);
} else {
return step(Empty.create(), rt.rest, newOpCtx);
}
// anon macro definition
} else if (head.token.type === parser.Token.Identifier &&
unwrapSyntax(head) === "macro" &&
resolve(head, context.phase) === "macro" &&
rest[0] && rest[0].token.value === "{}") {
return step(AnonMacro.create(rest[0].token.inner),
rest.slice(1),
opCtx);
// macro definition
} else if (head.token.type === parser.Token.Identifier &&
unwrapSyntax(head) === "macro" &&
resolve(head, context.phase) === "macro") {
var nameTokens = [];
if (rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()") {
nameTokens = rest[0].token.inner;
} else {
nameTokens.push(rest[0])
}
if (rest[1] && rest[1].token.type === parser.Token.Delimiter) {
return step(Macro.create(nameTokens, rest[1].token.inner),
rest.slice(2),
opCtx);
} else {
throwSyntaxError("enforest", "Macro declaration must include body", rest[1]);
}
// operator definition
// unaryop (neg) 1 { macro { rule { $op:expr } => { $op } } }
} else if (head.token.type === parser.Token.Identifier &&
head.token.value === "unaryop" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.NumericLiteral &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2] && rest[2].token.value === "{}") {
var trans = enforest(rest[2].token.inner, context);
return step(OperatorDefinition.create(syn.makeValue("unary", head),
rest[0].token.inner,
rest[1],
null,
trans.result.body),
rest.slice(3),
opCtx);
// operator definition
// binaryop (neg) 1 left { macro { rule { $op:expr } => { $op } } }
} else if (head.token.type === parser.Token.Identifier &&
head.token.value === "binaryop" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.NumericLiteral &&
rest[2] && rest[2].token.type === parser.Token.Identifier &&
rest[3] && rest[3].token.type === parser.Token.Delimiter &&
rest[3] && rest[3].token.value === "{}") {
var trans = enforest(rest[3].token.inner, context);
return step(OperatorDefinition.create(syn.makeValue("binary", head),
rest[0].token.inner,
rest[1],
rest[2],
trans.result.body),
rest.slice(4),
opCtx);
// function definition
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Identifier &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "()" &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "{}") {
rest[1].token.inner = rest[1].token.inner;
rest[2].token.inner = rest[2].token.inner;
return step(NamedFun.create(head, null, rest[0],
rest[1],
rest[2]),
rest.slice(3),
opCtx);
// generator function definition
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
rest[0].token.value === "*" &&
rest[1] && rest[1].token.type === parser.Token.Identifier &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "()" &&
rest[3] && rest[3].token.type === parser.Token.Delimiter &&
rest[3].token.value === "{}") {
rest[2].token.inner = rest[2].token.inner;
rest[3].token.inner = rest[3].token.inner;
return step(NamedFun.create(head, rest[0], rest[1],
rest[2],
rest[3]),
rest.slice(4),
opCtx);
// anonymous function definition
} else if(head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
rest[0].token.inner = rest[0].token.inner;
rest[1].token.inner = rest[1].token.inner;
return step(AnonFun.create(head,
null,
rest[0],
rest[1]),
rest.slice(2),
opCtx);
// anonymous generator function definition
} else if(head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
rest[0].token.value === "*" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "()" &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "{}") {
rest[1].token.inner = rest[1].token.inner;
rest[2].token.inner = rest[2].token.inner;
return step(AnonFun.create(head,
rest[0],
rest[1],
rest[2]),
rest.slice(3),
opCtx);
// arrow function
} else if(((head.token.type === parser.Token.Delimiter &&
head.token.value === "()") ||
head.token.type === parser.Token.Identifier) &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
return step(ArrowFun.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// catch statement
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "catch" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
rest[0].token.inner = rest[0].token.inner;
rest[1].token.inner = rest[1].token.inner;
return step(CatchClause.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// this expression
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "this") {
return step(ThisExpression.create(head), rest, opCtx);
// literal
} else if (head.token.type === parser.Token.NumericLiteral ||
head.token.type === parser.Token.StringLiteral ||
head.token.type === parser.Token.BooleanLiteral ||
head.token.type === parser.Token.RegularExpression ||
head.token.type === parser.Token.NullLiteral) {
return step(Lit.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "import" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "{}" &&
rest[1] && unwrapSyntax(rest[1]) === "from" &&
rest[2] && rest[2].token.type === parser.Token.StringLiteral &&
rest[3] && unwrapSyntax(rest[3]) === "for" &&
rest[4] && unwrapSyntax(rest[4]) === "macros") {
var importRest;
if (rest[5] && rest[5].token.type === parser.Token.Punctuator &&
rest[5].token.value === ";") {
importRest = rest.slice(6);
} else {
importRest = rest.slice(5);
}
return step(ImportForMacros.create(rest[0], rest[2]), importRest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "import" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "{}" &&
rest[1] && unwrapSyntax(rest[1]) === "from" &&
rest[2] && rest[2].token.type === parser.Token.StringLiteral) {
var importRest;
if (rest[3] && rest[3].token.type === parser.Token.Punctuator &&
rest[3].token.value === ";") {
importRest = rest.slice(4);
} else {
importRest = rest.slice(3);
}
return step(Import.create(head, rest[0], rest[1], rest[2]), importRest, opCtx);
// export
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "export" &&
rest[0] && (rest[0].token.type === parser.Token.Identifier ||
rest[0].token.type === parser.Token.Keyword ||
rest[0].token.type === parser.Token.Punctuator ||
rest[0].token.type === parser.Token.Delimiter)) {
if (unwrapSyntax(rest[1]) !== ";" && toksAdjacent(rest[0], rest[1])) {
throwSyntaxError("enforest",
"multi-token macro/operator names must be wrapped in () when exporting",
rest[1]);
}
return step(Export.create(head, rest[0]), rest.slice(1), opCtx);
// identifier
} else if (head.token.type === parser.Token.Identifier) {
return step(Id.create(head), rest, opCtx);
// punctuator
} else if (head.token.type === parser.Token.Punctuator) {
return step(Punc.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "with") {
throwSyntaxError("enforest", "with is not supported in sweet.js", head);
// keyword
} else if (head.token.type === parser.Token.Keyword) {
return step(Keyword.create(head), rest, opCtx);
// Delimiter
} else if (head.token.type === parser.Token.Delimiter) {
return step(Delimiter.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Template) {
return step(Template.create(head), rest, opCtx);
// end of file
} else if (head.token.type === parser.Token.EOF) {
assert(rest.length === 0, "nothing should be after an EOF");
return step(EOF.create(head), [], opCtx);
} else {
// todo: are we missing cases?
assert(false, "not implemented");
}
}
// Potentially an infix macro
// This should only be invoked on runtime syntax terms
if (!head.isMacro && !head.isLetMacro && !head.isAnonMacro && !head.isOperatorDefinition &&
rest.length && nameInEnv(rest[0], rest.slice(1), context, context.phase) &&
getValueInEnv(rest[0], rest.slice(1), context, context.phase).isOp === false) {
var infLeftTerm = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var infTerm = PartialExpression.create(head.destruct(context), infLeftTerm, function() {
return step(head, [], opCtx);
});
var infPrevStx = tagWithTerm(infTerm, head.destruct(context)).reverse().concat(opCtx.prevStx);
var infPrevTerms = [infTerm].concat(opCtx.prevTerms);
var infRes = expandMacro(rest, context, {
prevStx: infPrevStx,
prevTerms: infPrevTerms
});
if (infRes.prevTerms && infRes.prevTerms.length < infPrevTerms.length) {
var infOpCtx = rewindOpCtx(opCtx, infRes);
return step(infRes.result[0], infRes.result.slice(1).concat(infRes.rest), infOpCtx);
} else {
return step(head, infRes.result.concat(infRes.rest), opCtx);
}
}
// done with current step so combine and continue on
var combResult = opCtx.combine(head);
if (opCtx.stack.length === 0) {
return {
result: combResult.term,
rest: rest,
prevStx: combResult.prevStx,
prevTerms: combResult.prevTerms
};
} else {
return step(combResult.term, rest, opCtx.stack[0]);
}
}
return step(toks[0], toks.slice(1), {
combine: function(t) {
return {
term: t,
prevStx: prevStx,
prevTerms: prevTerms
};
},
prec: 0,
stack: [],
op: null,
prevStx: prevStx,
prevTerms: prevTerms
});
}
function rewindOpCtx(opCtx, res) {
// If we've consumed all pending operators, we can just start over.
// It's important that we always thread the new prevStx and prevTerms
// through, otherwise the old ones will still persist.
if (!res.prevTerms.length ||
!res.prevTerms[0].isPartial) {
return _.extend({}, opCtx, {
combine: function(t) {
return {
term: t,
prevStx: res.prevStx,
prevTerms: res.prevTerms
};
},
prec: 0,
op: null,
stack: [],
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
// To rewind, we need to find the first (previous) pending operator. It
// acts as a marker in the opCtx to let us know how far we need to go
// back.
var op = null;
for (var i = 0; i < res.prevTerms.length; i++) {
if (!res.prevTerms[i].isPartial) {
break;
}
if (res.prevTerms[i].isPartialOperation) {
op = res.prevTerms[i];
break;
}
}
// If the op matches the current opCtx, we don't need to rewind
// anything, but we still need to persist the prevStx and prevTerms.
if (opCtx.op === op) {
return _.extend({}, opCtx, {
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
for (var i = 0; i < opCtx.stack.length; i++) {
if (opCtx.stack[i].op === op) {
return _.extend({}, opCtx.stack[i], {
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
}
assert(false, "Rewind failed.");
}
function get_expression(stx, context) {
if (stx[0].term) {
for (var termLen = 1; termLen < stx.length; termLen++) {
if (stx[termLen].term !== stx[0].term) {
break;
}
}
// Guard the termLen because we can have a multi-token term that
// we don't want to split. TODO: is there something we can do to
// get around this safely?
if (stx[0].term.isPartialExpression &&
termLen === stx[0].term.stx.length) {
var expr = stx[0].term.combine().result;
for (var i = 1, term = stx[0].term; i < stx.length; i++) {
if (stx[i].term !== term) {
if (term && term.isPartial) {
term = term.left;
i--;
} else {
break;
}
}
}
return {
result: expr,
rest: stx.slice(i)
};
} else if (stx[0].term.isExpr) {
return {
result: stx[0].term,
rest: stx.slice(termLen)
};
} else {
return {
result: null,
rest: stx
};
}
}
var res = enforest(stx, context);
if (!res.result || !res.result.isExpr) {
return {
result: null,
rest: stx
};
}
return res;
}
function tagWithTerm(term, stx) {
return stx.map(function(s) {
cloned newtok <- s.token;
s = syntaxFromToken(newtok, s);
s.term = term;
return s;
});
}
// mark each syntax object in the pattern environment,
// mutating the environment
function applyMarkToPatternEnv (newMark, env) {
/*
Takes a `match` object:
{
level: <num>,
match: [<match> or <syntax>]
}
where the match property is an array of syntax objects at the bottom (0) level.
Does a depth-first search and applys the mark to each syntax object.
*/
function dfs(match) {
if (match.level === 0) {
// replace the match property with the marked syntax
match.match = _.map(match.match, function(stx) {
return stx.mark(newMark);
});
} else {
_.each(match.match, function(match) {
dfs(match);
});
}
}
_.keys(env).forEach(function(key) {
dfs(env[key]);
});
}
// given the syntax for a macro, produce a macro transformer
// (Macro) -> (([...CSyntax]) -> ReadTree)
function loadMacroDef(body, context, phase) {
var expanded = body[0].destruct(context, {stripCompileTerm: true});
var stub = parser.read("()");
stub[0].token.inner = expanded;
var flattend = flatten(stub);
var bodyCode = codegen.generate(parser.parse(flattend, {phase: phase}));
var macroGlobal = {
makeValue: syn.makeValue,
makeRegex: syn.makeRegex,
makeIdent: syn.makeIdent,
makeKeyword: syn.makeKeyword,
makePunc: syn.makePunc,
makeDelim: syn.makeDelim,
filename: context.filename,
getExpr: function(stx) {
var r;
if (stx.length === 0) {
return {
success: false,
result: [],
rest: []
};
}
r = get_expression(stx, context);
return {
success: r.result !== null,
result: r.result === null ? [] : r.result.destruct(context),
rest: r.rest
};
},
getIdent: function(stx) {
if (stx[0] && stx[0].token.type === parser.Token.Identifier) {
return {
success: true,
result: [stx[0]],
rest: stx.slice(1)
};
}
return {
success: false,
result: [],
rest: stx
};
},
getLit: function(stx) {
if (stx[0] && patternModule.typeIsLiteral(stx[0].token.type)) {
return {
success: true,
result: [stx[0]],
rest: stx.slice(1)
};
}
return {
success: false,
result: [],
rest: stx
};
},
unwrapSyntax: syn.unwrapSyntax,
throwSyntaxError: throwSyntaxError,
throwSyntaxCaseError: throwSyntaxCaseError,
prettyPrint: syn.prettyPrint,
parser: parser,
__fresh: fresh,
_: _,
patternModule: patternModule,
getPattern: function(id) {
return context.patternMap.get(id);
},
getTemplate: function(id) {
assert(context.templateMap.has(id), "missing template");
return syn.cloneSyntaxArray(context.templateMap.get(id));
},
applyMarkToPatternEnv: applyMarkToPatternEnv,
mergeMatches: function(newMatch, oldMatch) {
newMatch.patternEnv = _.extend({}, oldMatch.patternEnv, newMatch.patternEnv);
return newMatch;
},
console: console
};
context.env.keys().forEach(key -> {
var val = context.env.get(key);
// load the compile time values into the global object
if (val && val.value) {
macroGlobal[key] = val.value;
}
});
var macroFn;
if (vm) {
macroFn = vm.runInNewContext("(function() { return " + bodyCode + " })()",
macroGlobal);
} else {
macroFn = scopedEval(bodyCode, macroGlobal);
}
return macroFn;
}
// similar to `parse1` in the honu paper
// @ ([...SyntaxObject], ExpanderContext) -> {
// terms: [...TermTreeObject],
// context: ExpanderContext,
// restStx: Undefined or [...SyntaxObject]
// }
function expandToTermTree(stx, context) {
assert(context, "expander context is required");
var f, head, prevStx, restStx, prevTerms, macroDefinition;
var rest = stx;
while (rest.length > 0) {
assert(rest[0].token, "expecting a syntax object");
f = enforest(rest, context, prevStx, prevTerms);
// head :: TermTree
head = f.result;
// rest :: [Syntax]
rest = f.rest;
if (!head) {
// no head means the expansions stopped prematurely (for stepping)
restStx = rest;
break;
}
var destructed = tagWithTerm(head, f.result.destruct(context));
prevTerms = [head].concat(f.prevTerms);
prevStx = destructed.reverse().concat(f.prevStx);
if (head.isImport) {
// record the import in the module record for easier access
context.moduleRecord.importEntries.push(head);
// load up the (possibly cached) import module
var importMod = loadImport(head, context);
// visiting an imported module loads the compiletime values
// into the compiletime environment for this phase
context = visit(importMod.term, importMod.record, context.phase, context);
// bind the imported names in the rest of the module
// todo: how to handle references before an import?
rest = bindImportInMod(head, rest, importMod.term, importMod.record, context, context.phase);
}
if (head.isImportForMacros) {
// record the import in the module record for easier access
context.moduleRecord.importEntries.push(head);
// load up the (possibly cached) import module
var importMod = loadImport(head, context);
// invoking an imported module loads the runtime values
// into the environment for this phase
context = invoke(importMod.term, importMod.record, context.phase + 1, context);
// visiting an imported module loads the compiletime values
// into the compiletime environment for this phase
context = visit(importMod.term, importMod.record, context.phase + 1, context);
// bind the imported names in the rest of the module
// todo: how to handle references before an import?
rest = bindImportInMod(head, rest, importMod.term, importMod.record, context, context.phase + 1);
}
if (head.isMacro && expandCount < maxExpands) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({},
context,
{phase: context.phase + 1})));
// and load the macro definition into the environment
macroDefinition = loadMacroDef(head.body, context, context.phase + 1);
var name = head.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, head.name[0]);
addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope);
context.env.names.set(name, true);
context.env.set(resolve(nameStx, context.phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: head.name
});
}
if (head.isLetMacro && expandCount < maxExpands) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({phase: context.phase + 1},
context)));
// and load the macro definition into the environment
macroDefinition = loadMacroDef(head.body, context, context.phase + 1);
var freshName = fresh();
var name = head.name.map(unwrapSyntax).join("");
var oldName = head.name;
var nameStx = syn.makeIdent(name, head.name[0]);
var renamedName = nameStx.rename(nameStx, freshName);
// store a reference to the full name in the props object.
// this allows us to communicate the original full name to
// `visit` later on.
renamedName.props.fullName = oldName;
head.name = [renamedName];
rest = _.map(rest, function(stx) {
return stx.rename(nameStx, freshName);
});
context.env.names.set(name, true);
context.env.set(resolve(renamedName, context.phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: oldName
});
}
if (head.isOperatorDefinition) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({phase: context.phase + 1},
context)));
// and load the macro definition into the environment
var opDefinition = loadMacroDef(head.body, context, context.phase + 1);
var name = head.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, head.name[0]);
addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope);
var resolvedName = resolve(nameStx, context.phase);
var opObj = context.env.get(resolvedName);
if (!opObj) {
opObj = {
isOp: true,
builtin: builtinMode,
fullName: head.name
}
}
assert(unwrapSyntax(head.type) === "binary" ||
unwrapSyntax(head.type) === "unary",
"operator must either be binary or unary");
opObj[unwrapSyntax(head.type)] = {
fn: opDefinition,
prec: head.prec.token.value,
assoc: head.assoc ? head.assoc.token.value : null
};
context.env.names.set(name, true);
context.env.set(resolvedName, opObj);
}
if (head.isNamedFun) {
addToDefinitionCtx([head.name], context.defscope, true, context.paramscope);
}
if (head.isVariableStatement ||
head.isLetStatement ||
head.isConstStatement) {
addToDefinitionCtx(_.map(head.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
if(head.isBlock && head.body.isDelimiter) {
head.body.delim.token.inner.forEach(function(term) {
if (term.isVariableStatement) {
addToDefinitionCtx(_.map(term.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
});
}
if(head.isDelimiter) {
head.delim.token.inner.forEach(function(term) {
if (term.isVariableStatement) {
addToDefinitionCtx(_.map(term.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
});
}
if (head.isForStatement) {
var forCond = head.cond.token.inner;
if(forCond[0] && resolve(forCond[0], context.phase) === "let" &&
forCond[1] && forCond[1].token.type === parser.Token.Identifier) {
var letNew = fresh();
var letId = forCond[1];
forCond = forCond.map(function(stx) {
return stx.rename(letId, letNew);
});
// hack: we want to do the let renaming here, not
// in the expansion of `for (...)` so just remove the `let`
// keyword
head.cond.token.inner = expand([forCond[0]], context)
.concat(expand(forCond.slice(1), context));
// nice and easy case: `for (...) { ... }`
if (rest[0] && rest[0].token.value === "{}") {
rest[0] = rest[0].rename(letId, letNew);
} else {
// need to deal with things like `for (...) if (...) log(...)`
var bodyEnf = enforest(rest, context);
var bodyDestructed = bodyEnf.result.destruct(context);
var renamedBodyTerm = bodyEnf.result.rename(letId, letNew);
tagWithTerm(renamedBodyTerm, bodyDestructed);
rest = bodyEnf.rest;
prevStx = bodyDestructed.reverse().concat(prevStx);
prevTerms = [renamedBodyTerm].concat(prevTerms);
}
} else {
head.cond.token.inner = expand(head.cond.token.inner, context);
}
}
}
return {
// prevTerms are stored in reverse for the purposes of infix
// lookbehind matching, so we need to re-reverse them.
terms: prevTerms ? prevTerms.reverse() : [],
restStx: restStx,
context: context,
};
}
function addToDefinitionCtx(idents, defscope, skipRep, paramscope) {
assert(idents && idents.length > 0, "expecting some variable identifiers");
// flag for skipping repeats since we reuse this function to place both
// variables declarations (which need to skip redeclarations) and
// macro definitions which don't
skipRep = skipRep || false;
_.chain(idents)
.filter(function(id) {
if (skipRep) {
/*
When var declarations repeat in the same function scope:
var x = 24;
...
var x = 42;
we just need to use the first renaming and leave the
definition context as is.
*/
var varDeclRep = _.find(defscope, function(def) {
return def.id.token.value === id.token.value &&
arraysEqual(marksof(def.id.context), marksof(id.context));
});
/*
When var declaration repeat one of the function parameters:
function foo(x) {
var x;
}
we don't need to add the var to the definition context.
*/
var paramDeclRep = _.find(paramscope, function(param) {
return param.token.value === id.token.value &&
arraysEqual(marksof(param.context), marksof(id.context));
});
return (typeof varDeclRep === 'undefined') &&
(typeof paramDeclRep === 'undefined');
}
return true;
}).each(function(id) {
var name = fresh();
defscope.push({
id: id,
name: name
});
});
}
// similar to `parse2` in the honu paper except here we
// don't generate an AST yet
// @ (TermTreeObject, ExpanderContext) -> TermTreeObject
function expandTermTreeToFinal (term, context) {
assert(context && context.env, "environment map is required");
if (term.isArrayLiteral) {
term.array.delim.token.inner = expand(term.array.delim.token.inner, context);
return term;
} else if (term.isBlock) {
term.body.delim.token.inner = expand(term.body.delim.token.inner, context);
return term;
} else if (term.isParenExpression) {
term.args = _.map(term.args, function(arg) {
return expandTermTreeToFinal(arg, context);
});
return term;
} else if (term.isCall) {
term.fun = expandTermTreeToFinal(term.fun, context);
term.args = expandTermTreeToFinal(term.args, context);
return term;
} else if (term.isReturnStatement) {
term.expr = expandTermTreeToFinal(term.expr, context);
return term;
} else if (term.isUnaryOp) {
term.expr = expandTermTreeToFinal(term.expr, context);
return term;
} else if (term.isBinOp || term.isAssignmentExpression) {
term.left = expandTermTreeToFinal(term.left, context);
term.right = expandTermTreeToFinal(term.right, context);
return term;
} else if (term.isObjGet) {
term.left = expandTermTreeToFinal(term.left, context);
term.right.delim.token.inner = expand(term.right.delim.token.inner, context);
return term;
} else if (term.isObjDotGet) {
term.left = expandTermTreeToFinal(term.left, context);
term.right = expandTermTreeToFinal(term.right, context);
return term;
} else if (term.isConditionalExpression) {
term.cond = expandTermTreeToFinal(term.cond, context);
term.tru = expandTermTreeToFinal(term.tru, context);
term.fls = expandTermTreeToFinal(term.fls, context);
return term;
} else if (term.isVariableDeclaration) {
if (term.init) {
term.init = expandTermTreeToFinal(term.init, context);
}
return term;
} else if (term.isVariableStatement) {
term.decls = _.map(term.decls, function(decl) {
return expandTermTreeToFinal(decl, context);
});
return term;
} else if (term.isDelimiter) {
// expand inside the delimiter and then continue on
term.delim.token.inner = expand(term.delim.token.inner, context);
return term;
} else if (term.isNamedFun ||
term.isAnonFun ||
term.isCatchClause ||
term.isArrowFun ||
term.isModule) {
// function definitions need a bunch of hygiene logic
// push down a fresh definition context
var newDef = [];
var paramSingleIdent = term.params && term.params.token.type === parser.Token.Identifier;
var params;
if (term.params && term.params.token.type === parser.Token.Delimiter) {
params = term.params;
} else if (paramSingleIdent) {
params = term.params;
} else {
params = syn.makeDelim("()", [], null);
}
var bodies;
if (Array.isArray(term.body)) {
bodies = syn.makeDelim("{}", term.body, null);
} else {
bodies = term.body;
}
bodies = bodies.addDefCtx(newDef);
var paramNames = _.map(getParamIdentifiers(params), function(param) {
var freshName = fresh();
return {
freshName: freshName,
originalParam: param,
renamedParam: param.rename(param, freshName)
};
});
var bodyContext = makeExpanderContext(_.defaults({
defscope: newDef,
// paramscope is used to filter out var redeclarations
paramscope: paramNames.map(function(p) {
return p.renamedParam;
})
}, context));
// rename the function body for each of the parameters
var renamedBody = _.reduce(paramNames, function(accBody, p) {
return accBody.rename(p.originalParam, p.freshName)
}, bodies);
renamedBody = renamedBody;
var expandedResult = expandToTermTree(renamedBody.token.inner, bodyContext);
var bodyTerms = expandedResult.terms;
if(expandedResult.restStx) {
// The expansion was halted prematurely. Just stop and
// return what we have so far, along with the rest of the syntax
renamedBody.token.inner = expandedResult.terms.concat(expandedResult.restStx);
if(Array.isArray(term.body)) {
term.body = renamedBody.token.inner;
}
else {
term.body = renamedBody;
}
return term;
}
var renamedParams = _.map(paramNames, function(p) { return p.renamedParam});
var flatArgs;
if (paramSingleIdent) {
flatArgs = renamedParams[0];
} else {
var puncCtx = (term.params || null);
flatArgs = syn.makeDelim("()",
joinSyntax(renamedParams, syn.makePunc(",", puncCtx)),
puncCtx);
}
var expandedArgs = expand([flatArgs], bodyContext);
assert(expandedArgs.length === 1, "should only get back one result");
// stitch up the function with all the renamings
if (term.params) {
term.params = expandedArgs[0];
}
bodyTerms = _.map(bodyTerms, function(bodyTerm) {
// add the definition context to the result of
// expansion (this makes sure that syntax objects
// introduced by expansion have the def context)
if (bodyTerm.isBlock) {
// we need to expand blocks before adding the defctx since
// blocks defer macro expansion.
var blockFinal = expandTermTreeToFinal(bodyTerm,
expandedResult.context);
return blockFinal.addDefCtx(newDef);
} else {
var termWithCtx = bodyTerm.addDefCtx(newDef);
// finish expansion
return expandTermTreeToFinal(termWithCtx,
expandedResult.context);
}
})
if (term.isModule) {
bodyTerms.forEach(bodyTerm -> {
if (bodyTerm.isExport) {
if (bodyTerm.name.token.type == parser.Token.Delimiter &&
bodyTerm.name.token.value === "{}") {
bodyTerm.name.token.inner
|> filterCommaSep
|> names -> names.forEach(name -> {
context.moduleRecord.exportEntries.push(name);
});
} else {
throwSyntaxError("expand", "not valid export type", bodyTerm.name);
}
}
});
}
renamedBody.token.inner = bodyTerms;
if (Array.isArray(term.body)) {
term.body = renamedBody.token.inner;
} else {
term.body = renamedBody;
}
// and continue expand the rest
return term;
}
// the term is fine as is
return term;
}
// @ let TermTree = {}
// similar to `parse` in the honu paper
// @ ([...SyntaxObject], ExpanderContext) -> [...TermTreeObject]
function expand(stx, context) {
assert(context, "must provide an expander context");
var trees = expandToTermTree(stx, context);
var terms = _.map(trees.terms, function(term) {
return expandTermTreeToFinal(term, trees.context);
});
if(trees.restStx) {
terms.push.apply(terms, trees.restStx);
}
return terms;
}
function makeExpanderContext(o) {
o = o || {};
var env = o.env || new StringMap();
if (!env.names) {
env.names = new StringMap();
}
return Object.create(Object.prototype, {
filename: {value: o.filename,
writable: false, enumerable: true, configurable: false},
env: {value: env,
writable: false, enumerable: true, configurable: false},
defscope: {value: o.defscope,
writable: false, enumerable: true, configurable: false},
paramscope: {value: o.paramscope,
writable: false, enumerable: true, configurable: false},
templateMap: {value: o.templateMap || new StringMap(),
writable: false, enumerable: true, configurable: false},
patternMap: {value: o.patternMap || new StringMap(),
writable: false, enumerable: true, configurable: false},
mark: {value: o.mark,
writable: false, enumerable: true, configurable: false},
phase: {value: o.phase,
writable: false, enumerable: true, configurable: false},
implicitImport: {value: o.implicitImport || new StringMap(),
writable: false, enumerable: true, configurable: false},
moduleRecord: {value: o.moduleRecord || {},
writable: false, enumerable: true, configurable: false}
});
}
function makeModuleExpanderContext(filename, templateMap, patternMap, phase, moduleRecord) {
return makeExpanderContext({
filename: filename,
templateMap: templateMap,
patternMap: patternMap,
phase: phase,
moduleRecord: moduleRecord
});
}
function makeTopLevelExpanderContext(options) {
var filename = options && options.filename ? options.filename : "<anonymous module>";
return makeExpanderContext({
filename: filename,
});
}
// a hack to make the top level hygiene work out
function expandTopLevel(stx, moduleContexts, options) {
moduleContexts = moduleContexts || [];
options = options || {};
options.flatten = options.flatten != null ? options.flatten : true;
maxExpands = options.maxExpands || Infinity;
expandCount = 0;
var context = makeTopLevelExpanderContext(options);
var modBody = syn.makeDelim("{}", stx, null);
modBody = _.reduce(moduleContexts, function(acc, mod) {
context.env.extend(mod.env);
context.env.names.extend(mod.env.names);
return loadModuleExports(acc, context.env, mod.exports, mod.env);
}, modBody);
var res = expand([syn.makeIdent("module", null), modBody], context);
res = res[0].destruct(context, {stripCompileTerm: true});
res = res[0].token.inner;
return options.flatten ? flatten(res) : res;
}
// @ (Str, Str) -> Str
function resolvePath(name, parent) {
var path = require("path");
var resolveSync = require("resolve/lib/sync");
var root = path.dirname(parent);
var fs = require("fs");
if (name[0] === ".") {
name = path.resolve(root, name);
}
return resolveSync(name, {
basedir: root,
extensions: ['.js', '.sjs']
});
}
// (Str) -> [...SyntaxObject]
function defaultImportStx(importPath, ctx) {
var names = [
"quoteSyntax",
"syntax",
"#",
"syntaxCase",
"macro",
"withSyntax",
"letstx",
"macroclass",
"operator"
];
var importNames = names.map(name -> syn.makeIdent(name, ctx));
var importForMacrosNames = names.map(name -> syn.makeIdent(name, ctx));
// import { names ... } from "importPath" for macros
var importForMacrosStmt = [syn.makeKeyword("import", ctx),
syn.makeDelim("{}", joinSyntax(importForMacrosNames,
syn.makePunc(",", ctx)),
ctx),
syn.makeIdent("from", ctx),
syn.makeValue(importPath, ctx),
syn.makeKeyword("for", ctx),
syn.makeIdent("macros", ctx)];
// import { names ... } from "importPath"
var importStmt = [syn.makeKeyword("import", ctx),
syn.makeDelim("{}", joinSyntax(importNames,
syn.makePunc(",", ctx)),
ctx),
syn.makeIdent("from", ctx),
syn.makeValue(importPath, ctx)];
return importStmt.concat(importForMacrosStmt);
}
// @ (Str, [...SyntaxObject]) -> {
// record: ModuleRecord,
// term: ModuleTerm
// }
function createModule(name, body) {
var language = "base";
var modBody = body;
if (body && body[0] && body[1] && body[2] &&
unwrapSyntax(body[0]) === "#" &&
unwrapSyntax(body[1]) === "lang" &&
body[2].token.type === parser.Token.StringLiteral) {
language = unwrapSyntax(body[2]);
// consume optional semicolon
modBody = body[3] && body[3].token.value === ";" &&
body[3].token.type == parser.Token.Punctuator ? body.slice(4) : body.slice(3);
}
// insert the default import statements into the module body
if (language !== "base" && language !== "js") {
// "base" and "js" are currently special languages meaning don't
// insert the default imports
modBody = defaultImportStx(language, body[0]).concat(modBody);
}
return {
record: {
name: name,
language: language,
importEntries: [],
exportEntries: []
},
term: Module.create(modBody)
};
}
// @ (Str) -> {
// record: ModuleRecord,
// term: ModuleTerm
// }
function loadModule(name) {
// node specific code
var fs = require("fs");
return fs.readFileSync(name, 'utf8')
|> parser.read |> body -> {
return createModule(name, body)
};
}
// For a given module, phase, and context load the runtime values
// into the context and return the modified context
// @ (ModuleTerm, ModuleRecord, Num, ExpanderContext) -> ExpanderContext
function invoke(modTerm, modRecord, phase, context) {
if (modRecord.language === "base") {
// base modules can just use the normal require pipeline
var exported = require(modRecord.name);
Object.keys(exported).forEach(exp -> {
// create new bindings in the context
var freshName = fresh();
var expName = syn.makeIdent(exp, null);
var renamed = expName.rename(expName, freshName)
modRecord.exportEntries.push(renamed);
context.env.set(resolve(renamed, phase), {
value: exported[exp]
});
context.env.names.set(exp, true);
})
} else {
// recursively invoke any imports in this module at this
// phase and update the context
modRecord.importEntries.forEach(imp -> {
var importMod = loadImport(imp, context);
if (imp.isImport) {
context = invoke(importMod.term, importMod.record, phase, context);
}
});
// turn the module into text so we can eval it
var code = modTerm.body
|> terms -> terms.map(term -> term.destruct(context, {stripCompileTerm: true,
stripModuleTerm: true}))
|> _.flatten
|> flatten
|> parser.parse
|> codegen.generate
var global = {
console: console
};
// eval but with a fresh heap
vm.runInNewContext(code, global);
// update the exports with the runtime values
modRecord.exportEntries.forEach(exp -> {
var expName = resolve(exp, phase);
var expVal = global[expName];
context.env.set(expName, {value: expVal});
context.env.names.set(unwrapSyntax(exp), true);
});
}
return context;
}
// For a given module, phase, and context, load the compiletime values into
// the context and return the modified context
// @ (ModuleTerm, ModuleRecord, Num, ExpanderContext) -> ExpanderContext
function visit(modTerm, modRecord, phase, context) {
var defctx = [];
// don't need to visit base modules since they do not support macros
if (modRecord.language === "base") {
return context;
}
// add a visiting definition context since we are binding
// macros in the module scope
modTerm.body = modTerm.body.map(term -> term.addDefCtx(defctx));
// reset the exports
modRecord.exportEntries = [];
// for each of the imported modules, recursively visit and
// invoke them at the appropriate phase and then bind the
// imported names in this module
modRecord.importEntries.forEach(imp -> {
var importMod = loadImport(imp, context);
if(imp.isImport) {
context = visit(importMod.term, importMod.record, phase, context);
} else if (imp.isImportForMacros) {
context = invoke(importMod.term, importMod.record, phase + 1, context);
context = visit(importMod.term, importMod.record, phase + 1, context);
} else {
// todo: arbitrary phase
assert(false, "not implemented yet");
}
modTerm.body = bindImportInMod(imp,
modTerm.body,
importMod.term,
importMod.record,
context,
phase);
});
// go through the module and load any compiletime values in to the context
modTerm.body.forEach(term -> {
var name;
var macroDefinition;
if (term.isMacro) {
macroDefinition = loadMacroDef(term.body, context, phase + 1);
name = unwrapSyntax(term.name[0]);
context.env.names.set(name, true);
context.env.set(resolve(term.name[0], phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: term.name
});
}
if (term.isLetMacro) {
macroDefinition = loadMacroDef(term.body, context, phase + 1);
// compilation collapses multi-token let macro names into single identifier
name = unwrapSyntax(term.name[0]);
context.env.names.set(name, true);
context.env.set(resolve(term.name[0], phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: term.name[0].props.fullName
});
}
if (term.isOperatorDefinition) {
var opDefinition = loadMacroDef(term.body, context, phase + 1);
name = term.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, term.name[0]);
addToDefinitionCtx([nameStx], defctx, false, []);
var resolvedName = resolve(nameStx, phase);
var opObj = context.env.get(resolvedName);
if (!opObj) {
opObj = {
isOp: true,
builtin: builtinMode,
fullName: term.name
}
}
assert(unwrapSyntax(term.type) === "binary" ||
unwrapSyntax(term.type) === "unary",
"operator must either be binary or unary");
opObj[unwrapSyntax(term.type)] = {
fn: opDefinition,
prec: term.prec.token.value,
assoc: term.assoc ? term.assoc.token.value : null
};
context.env.names.set(name, true);
context.env.set(resolvedName, opObj);
}
// add the exported names to the module record
if (term.isExport) {
if (term.name.token.type === parser.Token.Delimiter &&
term.name.token.value === "{}") {
term.name.token.inner
|> filterCommaSep
|> names -> names.forEach(name -> {
modRecord.exportEntries.push(name);
});
} else {
throwSyntaxError("visit", "not valid export", term.name);
}
}
});
return context;
}
// a version of map where the callback only runs on the non comma items in
// the comma separated list.
function mapCommaSep(l, f) {
return l.map((stx, idx)-> {
if (idx % 2 !== 0 && (stx.token.type !== parser.Token.Punctuator ||
stx.token.value !== ",")) {
throwSyntaxError("import",
"expecting a comma separated list",
stx);
} else if (idx % 2 !== 0) {
return stx;
} else {
return f(stx);
}
});
}
function filterCommaSep(stx) {
return stx.filter((stx, idx) -> {
if (idx % 2 !== 0 && (stx.token.type !== parser.Token.Punctuator ||
stx.token.value !== ",")) {
throwSyntaxError("import",
"expecting a comma separated list",
stx);
} else if (idx % 2 !== 0) {
return false;
} else {
return true;
}
});
}
// @ (ImportTerm, ExpanderContext) -> {
// term: ModuleTerm
// record: ModuleRecord
// }
function loadImport(imp, context) {
var modFullPath = resolvePath(unwrapSyntax(imp.from), context.filename);
if(!availableModules.has(modFullPath)) {
// load it
var modToImport = loadModule(modFullPath)
|> mod -> expandModule(mod.term,
modFullPath,
context.templateMap,
context.patternMap,
mod.record);
var modPair = {
term: modToImport.mod,
record: modToImport.context.moduleRecord
};
availableModules.set(modFullPath, modPair);
return modPair;
}
return availableModules.get(modFullPath);
}
// @ (ImportTerm, [...SyntaxObject], ModuleTerm, ModuleRecord, ExpanderContext, Num) -> Void
function bindImportInMod(imp, stx, modTerm, modRecord, context, phase) {
// todo: implement other import forms
if (imp.names.token.type !== parser.Token.Delimiter) {
assert(false, "not implemented yet");
}
if (imp.names.token.inner.length === 0) {
throwSyntaxCaseError("compileModule",
"must include names to import",
imp.names);
}
// first collect the import names and their associated bindings
var renamedNames = imp.names.token.inner
|> filterCommaSep
|> names -> names.map(importName -> {
var isBase = modRecord.language === "base";
var inExports = _.find(modRecord.exportEntries, expTerm -> {
if (importName.token.type === parser.Token.Delimiter) {
return expTerm.token.type === parser.Token.Delimiter &&
syntaxInnerValuesEq(importName, expTerm);
}
return expTerm.token.value === importName.token.value
});
if (!(inExports || isBase)) {
throwSyntaxError("compile",
"the imported name `" +
unwrapSyntax(importName) +
"` was not exported from the module",
importName);
}
var exportName, trans, exportNameStr;
if (!inExports) {
// case when importing from a non ES6
// module but not for macros so the module
// was not invoked and thus nothing in the
// context for this name
if (importName.token.type === parser.Token.Delimiter) {
exportNameStr = importName.map(unwrapSyntax).join('');
} else {
exportNameStr = unwrapSyntax(importName);
}
trans = null;
} else if (inExports.token.type === parser.Token.Delimiter) {
exportName = inExports.token.inner;
exportNameStr = exportName.map(unwrapSyntax).join('');
trans = getValueInEnv(exportName[0],
exportName.slice(1),
context,
phase);
} else {
exportName = inExports;
exportNameStr = unwrapSyntax(exportName);
trans = getValueInEnv(exportName,
[],
context,
phase);
}
var newParam = syn.makeIdent(exportNameStr, importName);
var newName = fresh();
return {
original: newParam,
renamed: newParam.imported(newParam, newName, phase),
name: newName,
trans: trans
};
});
// set the new bindings in the context
renamedNames.forEach(name -> {
context.env.names.set(unwrapSyntax(name.renamed), true);
context.env.set(resolve(name.renamed, phase),
name.trans);
// setup a reverse map from each import name to
// the import term but only for runtime values
if (name.trans === null || (name.trans && name.trans.value)) {
var resolvedName = resolve(name.renamed, phase);
var origName = resolve(name.original, phase);
context.implicitImport.set(resolvedName, imp);
}
});
imp.names = syn.makeDelim("{}",
joinSyntax(renamedNames.map(name -> name.renamed),
syn.makePunc(",", imp.names)),
imp.names);
return stx.map(stx -> renamedNames.reduce((acc, name) -> {
return acc.imported(name.original, name.name, phase);
}, stx));
}
// (ModuleTerm, Str, Map, Map, ModuleRecord) -> {
// context: ExpanderContext,
// mod: ModuleTerm
// }
function expandModule(mod, filename, templateMap, patternMap, moduleRecord) {
// create a new expander context for this module
var context = makeModuleExpanderContext(filename,
templateMap,
patternMap,
0,
moduleRecord);
return {
context: context,
mod: expandTermTreeToFinal(mod, context)
};
}
function filterCompileNames(stx, context) {
assert(stx.token.type === parser.Token.Delimiter, "must be a delimter");
var runtimeNames = stx.token.inner
|> filterCommaSep
|> names -> {
return names.filter(name -> {
if (name.token.type === parser.Token.Delimiter) {
return !nameInEnv(name.token.inner[0],
name.token.inner.slice(1),
context,
0);
} else {
return !nameInEnv(name, [], context, 0);
}
});
};
var newInner = runtimeNames.reduce((acc, name, idx, orig) -> {
acc.push(name);
if (orig.length - 1 !== idx) { // don't add trailing comma
acc.push(syn.makePunc(",", name));
}
return acc;
}, []);
return syn.makeDelim("{}", newInner, stx);
}
// Takes an expanded module term and flattens it.
// @ (ModuleTerm, SweetOptions, TemplateMap, PatternMap) -> [...SyntaxObject]
function flattenModule(modTerm, modRecord, context) {
// filter the imports to just the imports and names that are
// actually available at runtime
var imports = modRecord.importEntries.reduce((acc, imp) -> {
if (imp.isImportForMacros) {
return acc;
}
if (imp.names.token.type === parser.Token.Delimiter) {
imp.names = filterCompileNames(imp.names, context);
if (imp.names.token.inner.length === 0) {
return acc;
}
return acc.concat(imp);
} else {
assert(false, "not implemented yet");
}
}, []);
// filter the exports to just the exports and names that are
// actually available at runtime
var output = modTerm.body.reduce((acc, term) -> {
if (term.isExport) {
if (term.name.token.type === parser.Token.Delimiter) {
term.name = filterCompileNames(term.name, context);
if (term.name.token.inner.length === 0) {
return acc;
}
} else {
assert(false, "not implemented yet");
}
}
return acc.concat(term.destruct(context, {stripCompileTerm: true,
stripModuleTerm: true}));
}, []);
output = output
|> flatten
|> output -> output.map(stx -> {
var name = resolve(stx, 0);
// collect the implicit imports (those imports that
// must be included because a macro expanded to a reference
// to an import from some other module)
if (context.implicitImport.has(name)) {
imports.push(context.implicitImport.get(name));
}
return stx
});
// flatten everything
var flatImports = imports.reduce((acc, imp) -> {
return acc.concat(flatten(imp.destruct(context).concat(syn.makePunc(";", imp.names))));
}, []);
return {
imports: imports,
body: flatImports.concat(output)
};
}
function flattenImports(imports, mod, context) {
return imports.reduce((acc, imp) -> {
var modFullPath = resolvePath(unwrapSyntax(imp.from), context.filename);
if (availableModules.has(modFullPath)) {
var modPair = availableModules.get(modFullPath);
var flattened = flattenModule(modPair.term, modPair.record, context);
acc.push({
path: modFullPath,
code: flattened.body
});
acc = acc.concat(flattenImports(flattened.imports, mod, context))
return acc;
} else {
assert(false, "module was unexpectedly not available for compilation" + modFullPath);
}
}, []);
}
// The entry point to expanding with modules. Starting from the
// token tree of a module, compile it and all its imports. Return
// an array of all the compiled modules.
// @ ([...SyntaxObject], {filename: Str}) -> [...{ path: Str, code: [...SyntaxObject]}]
function compileModule(stx, options) {
var fs = require("fs");
var filename = options && typeof options.filename !== 'undefined'
? fs.realpathSync(options.filename)
: "(anonymous module)";
maxExpands = Infinity;
expandCount = 0;
var mod = createModule(filename, stx);
// the template and pattern maps are global for every module
var templateMap = new StringMap();
var patternMap = new StringMap();
availableModules = new StringMap();
var expanded = expandModule(mod.term, filename, templateMap, patternMap, mod.record);
var flattened = flattenModule(expanded.mod, expanded.context.moduleRecord, expanded.context);
var compiledModules = flattenImports(flattened.imports, expanded.mod, expanded.context);
return [{
path: filename,
code: flattened.body
}].concat(compiledModules);
}
function loadModuleExports(stx, newEnv, exports, oldEnv) {
return _.reduce(exports, function(acc, param) {
var newName = fresh();
var transformer = oldEnv.get(resolve(param.oldExport));
if (transformer) {
newEnv.set(resolve(param.newParam.rename(param.newParam, newName)),
transformer);
return acc.rename(param.newParam, newName);
} else {
return acc;
}
}, stx);
}
// break delimiter tree structure down to flat array of syntax objects
// @ ([...SyntaxObject]) -> [...SyntaxObject]
function flatten(stx) {
return _.reduce(stx, function(acc, stx) {
if (stx.token.type === parser.Token.Delimiter) {
var openParen = syntaxFromToken({
type: parser.Token.Punctuator,
value: stx.token.value[0],
range: stx.token.startRange,
sm_range: (typeof stx.token.sm_startRange == 'undefined'
? stx.token.startRange
: stx.token.sm_startRange),
lineNumber: stx.token.startLineNumber,
sm_lineNumber: (typeof stx.token.sm_startLineNumber == 'undefined'
? stx.token.startLineNumber
: stx.token.sm_startLineNumber),
lineStart: stx.token.startLineStart,
sm_lineStart: (typeof stx.token.sm_startLineStart == 'undefined'
? stx.token.startLineStart
: stx.token.sm_startLineStart)
}, stx);
var closeParen = syntaxFromToken({
type: parser.Token.Punctuator,
value: stx.token.value[1],
range: stx.token.endRange,
sm_range: (typeof stx.token.sm_endRange == 'undefined'
? stx.token.endRange
: stx.token.sm_endRange),
lineNumber: stx.token.endLineNumber,
sm_lineNumber: (typeof stx.token.sm_endLineNumber == 'undefined'
? stx.token.endLineNumber
: stx.token.sm_endLineNumber),
lineStart: stx.token.endLineStart,
sm_lineStart: (typeof stx.token.sm_endLineStart == 'undefined'
? stx.token.endLineStart
: stx.token.sm_endLineStart)
}, stx);
if (stx.token.leadingComments) {
openParen.token.leadingComments = stx.token.leadingComments;
}
if (stx.token.trailingComments) {
openParen.token.trailingComments = stx.token.trailingComments;
}
acc.push(openParen);
push.apply(acc, flatten(stx.token.inner));
acc.push(closeParen);
return acc;
}
stx.token.sm_lineNumber = typeof stx.token.sm_lineNumber != 'undefined'
? stx.token.sm_lineNumber
: stx.token.lineNumber;
stx.token.sm_lineStart = typeof stx.token.sm_lineStart != 'undefined'
? stx.token.sm_lineStart
: stx.token.lineStart;
stx.token.sm_range = typeof stx.token.sm_range != 'undefined'
? stx.token.sm_range
: stx.token.range;
acc.push(stx);
return acc;
}, []);
}
exports.StringMap = StringMap;
exports.enforest = enforest;
exports.expand = expandTopLevel;
exports.compileModule = compileModule;
exports.resolve = resolve;
exports.get_expression = get_expression;
exports.getName = getName;
exports.getValueInEnv = getValueInEnv;
exports.nameInEnv = nameInEnv;
exports.makeExpanderContext = makeExpanderContext;
exports.Expr = Expr;
exports.VariableStatement = VariableStatement;
exports.tokensToSyntax = syn.tokensToSyntax;
exports.syntaxToTokens = syn.syntaxToTokens;
}));
| src/expander.js | #lang "../macros/stxcase.js";
/*
Copyright (C) 2012 Tim Disney <[email protected]>
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.
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 <COPYRIGHT HOLDER> 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 @ from "contracts.js"
(function (root, factory) {
if (typeof exports === 'object') {
// CommonJS
factory(exports,
require('underscore'),
require('./parser'),
require('./syntax'),
require('./scopedEval'),
require("./patterns"),
require('escodegen'),
require('vm'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports',
'underscore',
'parser',
'syntax',
'scopedEval',
'patterns',
'escodegen'], factory);
}
}(this, function(exports, _, parser, syn, se, patternModule, gen, vm) {
'use strict';
// escodegen still doesn't quite support AMD: https://github.com/Constellation/escodegen/issues/115
var codegen = typeof escodegen !== "undefined" ? escodegen : gen;
var assert = syn.assert;
var throwSyntaxError = syn.throwSyntaxError;
var throwSyntaxCaseError = syn.throwSyntaxCaseError;
var SyntaxCaseError = syn.SyntaxCaseError;
var unwrapSyntax = syn.unwrapSyntax;
macro (->) {
rule infix { $param:ident | { $body ... } } => {
function ($param) { $body ...}
}
rule infix { $param:ident | $body:expr } => {
function ($param) { return $body }
}
rule infix { ($param:ident (,) ...) | { $body ... } } => {
function ($param (,) ...) { $body ... }
}
rule infix { ($param:ident (,) ...) | $body:expr } => {
function ($param (,) ...) { return $body }
}
}
operator (|>) 1 left { $l, $r } => #{ $r($l) }
// used to export "private" methods for unit testing
exports._test = {};
function StringMap(o) {
this.__data = o || {};
}
StringMap.prototype = {
keys: function() {
return Object.keys(this.__data);
},
has: function(key) {
return Object.prototype.hasOwnProperty.call(this.__data, key);
},
get: function(key) {
return this.has(key) ? this.__data[key] : void 0;
},
set: function(key, value) {
this.__data[key] = value;
},
extend: function() {
var args = _.map(_.toArray(arguments), function(x) {
return x.__data;
});
_.extend.apply(_, [this.__data].concat(args));
return this;
}
}
var scopedEval = se.scopedEval;
var Rename = syn.Rename;
var Mark = syn.Mark;
var Def = syn.Def;
var Imported = syn.Imported;
var syntaxFromToken = syn.syntaxFromToken;
var joinSyntax = syn.joinSyntax;
var builtinMode = false;
var expandCount = 0;
var maxExpands;
var availableModules;
var push = Array.prototype.push;
function remdup(mark, mlist) {
if (mark === _.first(mlist)) {
return _.rest(mlist, 1);
}
return [mark].concat(mlist);
}
// (CSyntax) -> [...Num]
function marksof(ctx, stopName, originalName) {
while (ctx) {
if (ctx.constructor === Mark) {
return remdup(ctx.mark, marksof(ctx.context, stopName, originalName));
}
if(ctx.constructor === Def) {
ctx = ctx.context;
continue;
}
if (ctx.constructor === Rename) {
if(stopName === originalName + "$" + ctx.name) {
return [];
}
ctx = ctx.context;
continue;
}
if (ctx.constructor === Imported) {
ctx = ctx.context;
continue;
}
assert(false, "Unknown context type");
}
return [];
}
function resolve(stx, phase) {
assert(phase !== undefined, "must pass in phase");
return resolveCtx(stx.token.value, stx.context, [], [], {}, phase);
}
// This call memoizes intermediate results in the recursive invocation.
// The scope of the memo cache is the resolve() call, so that multiple
// resolve() calls don't walk all over each other, and memory used for
// the memoization can be garbage collected.
//
// The memoization addresses issue #232.
//
// It looks like the memoization uses only the context and doesn't look
// at originalName, stop_spine and stop_branch arguments. This is valid
// because whenever in every recursive call operates on a "deeper" or
// else a newly created context. Therefore the collection of
// [originalName, stop_spine, stop_branch] can all be associated with a
// unique context. This argument is easier to see in a recursive
// rewrite of the resolveCtx function than with the while loop
// optimization - https://gist.github.com/srikumarks/9847260 - where the
// recursive steps always operate on a different context.
//
// This might make it seem that the resolution results can be stored on
// the context object itself, but that would not work in general
// because multiple resolve() calls will walk over each other's cache
// results, which fails tests. So the memoization uses only a context's
// unique instance numbers as the memoization key and is local to each
// resolve() call.
//
// With this memoization, the time complexity of the resolveCtx call is
// no longer exponential for the cases in issue #232.
function resolveCtx(originalName, ctx, stop_spine, stop_branch, cache, phase) {
if (!ctx) { return originalName; }
var key = ctx.instNum;
return cache[key] || (cache[key] = resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache, phase));
}
// (Syntax) -> String
function resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache, phase) {
while (true) {
if (!ctx) { return originalName; }
if (ctx.constructor === Mark) {
ctx = ctx.context;
continue;
}
if (ctx.constructor === Def) {
if (stop_spine.indexOf(ctx.defctx) !== -1) {
ctx = ctx.context;
continue;
} else {
stop_branch = unionEl(stop_branch, ctx.defctx);
ctx = renames(ctx.defctx, ctx.context, originalName);
continue;
}
}
if (ctx.constructor === Rename) {
if (originalName === ctx.id.token.value) {
var idName = resolveCtx(ctx.id.token.value,
ctx.id.context,
stop_branch,
stop_branch,
cache,
0);
var subName = resolveCtx(originalName,
ctx.context,
unionEl(stop_spine, ctx.def),
stop_branch,
cache,
0);
if (idName === subName) {
var idMarks = marksof(ctx.id.context,
originalName + "$" + ctx.name,
originalName);
var subMarks = marksof(ctx.context,
originalName + "$" + ctx.name,
originalName);
if (arraysEqual(idMarks, subMarks)) {
return originalName + "$" + ctx.name;
}
}
}
ctx = ctx.context;
continue;
}
if (ctx.constructor === Imported) {
if (phase === ctx.phase) {
if (originalName === ctx.id.token.value) {
return originalName + "$" + ctx.name;
}
}
ctx = ctx.context;
continue;
}
assert(false, "Unknown context type");
}
}
function arraysEqual(a, b) {
if(a.length !== b.length) {
return false;
}
for(var i = 0; i < a.length; i++) {
if(a[i] !== b[i]) {
return false;
}
}
return true;
}
function renames(defctx, oldctx, originalName) {
var acc = oldctx;
for (var i = 0; i < defctx.length; i++) {
if (defctx[i].id.token.value === originalName) {
acc = new Rename(defctx[i].id, defctx[i].name, acc, defctx);
}
}
return acc;
}
function unionEl(arr, el) {
if (arr.indexOf(el) === -1) {
var res = arr.slice(0);
res.push(el);
return res;
}
return arr;
}
var nextFresh = 0;
// @ () -> Num
function fresh() { return nextFresh++; }
// wraps the array of syntax objects in the delimiters given by the second argument
// ([...CSyntax], CSyntax) -> [...CSyntax]
function wrapDelim(towrap, delimSyntax) {
assert(delimSyntax.token.type === parser.Token.Delimiter,
"expecting a delimiter token");
return syntaxFromToken({
type: parser.Token.Delimiter,
value: delimSyntax.token.value,
inner: towrap,
range: delimSyntax.token.range,
startLineNumber: delimSyntax.token.startLineNumber,
lineStart: delimSyntax.token.lineStart
}, delimSyntax);
}
// (CSyntax) -> [...CSyntax]
function getParamIdentifiers(argSyntax) {
if (argSyntax.token.type === parser.Token.Delimiter) {
return _.filter(argSyntax.token.inner, function(stx) { return stx.token.value !== ","});
} else if (argSyntax.token.type === parser.Token.Identifier) {
return [argSyntax];
} else {
assert(false, "expecting a delimiter or a single identifier for function parameters");
}
}
function inherit(parent, child, methods) {
var P = function(){};
P.prototype = parent.prototype;
child.prototype = new P();
child.prototype.constructor = child;
_.extend(child.prototype, methods);
}
macro cloned {
rule { $dest:ident <- $source:expr ;... } => {
var src = $source;
var keys = Object.keys(src);
var $dest = {};
for (var i = 0, len = keys.length, key; i < len; i++) {
key = keys[i];
$dest[key] = src[key];
}
}
}
macro to_str {
case { _ ($toks (,) ...) } => {
var toks = #{ $toks ... };
// We aren't using unwrapSyntax because it breaks since its defined
// within the outer scope! We need phases.
var str = toks.map(function(x) { return x.token.value }).join('');
return [makeValue(str, #{ here })];
}
}
macro class_method {
rule { $name:ident $args $body } => {
to_str($name): function $args $body
}
}
macro class_extend {
rule { $name $parent $methods } => {
inherit($parent, $name, $methods);
}
}
macro class_ctr {
rule { $name ($field ...) } => {
function $name($field (,) ...) {
$(this.$field = $field;) ...
}
}
}
macro class_create {
rule { $name ($arg (,) ...) } => {
$name.properties = [$(to_str($arg)) (,) ...];
$name.create = function($arg (,) ...) {
return new $name($arg (,) ...);
}
}
}
macro dataclass {
rule {
$name:ident ($field:ident (,) ...) extends $parent:ident {
$methods:class_method ...
} ;...
} => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
class_extend $name $parent {
to_str('is', $name): true,
$methods (,) ...
}
}
rule {
$name:ident ($field:ident (,) ...) {
$methods:class_method ...
} ;...
} => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
$name.prototype = {
to_str('is', $name): true,
$methods (,) ...
};
}
rule { $name:ident ($field (,) ...) extends $parent:ident ;... } => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
class_extend $name $parent {
to_str('is', $name): true
}
}
rule { $name:ident ($field (,) ...) ;... } => {
class_ctr $name ($field ...)
class_create $name ($field (,) ...)
$name.prototype = {
to_str('is', $name): true
};
}
}
// @ let TemplateMap = {}
// @ let PatternMap = {}
// @ let TokenObject = {}
// @ let ContextObject = {}
// @ let SyntaxObject = {
// token: TokenObject,
// context: Null or ContextObject
// }
// @ let TermTreeObject = {}
// @ let ExpanderContext = {}
// {
// filename: Str,
// requireModule: Str,
// env: {},
// defscope: {},
// paramscope: {},
// templateMap: {},
// patternMap: {},
// mark: Num
// }
// @ let ExportTerm = {
// name: SyntaxObject
// }
// @ let ImportTerm = {
// names: SyntaxObject,
// from: SyntaxObject
// }
// @ let ModuleTerm = {
// name: SyntaxObject,
// lang: SyntaxObject,
// body: [...SyntaxObject] or [...TermTreeObject],
// imports: [...ImportTerm],
// exports: [...ExportTerm]
// }
// A TermTree is the core data structure for the macro expansion process.
// It acts as a semi-structured representation of the syntax.
dataclass TermTree() {
// Go back to the syntax object representation. Uses the
// ordered list of properties that each subclass sets to
// determine the order in which multiple children are
// destructed.
// ({stripCompileTerm: ?Boolean}) -> [...Syntax]
destruct(context, options) {
assert(context, "must pass in the context to destruct");
options = options || {};
var self = this;
if (options.stripCompileTerm && this.isCompileTimeTerm) {
return [];
}
if (options.stripModuleTerm && this.isModuleTerm) {
return [];
}
return _.reduce(this.constructor.properties, function(acc, prop) {
if (self[prop] && self[prop].isTermTree) {
push.apply(acc, self[prop].destruct(context, options));
return acc;
} else if (self[prop] && self[prop].token && self[prop].token.inner) {
cloned newtok <- self[prop].token;
var clone = syntaxFromToken(newtok, self[prop]);
clone.token.inner = _.reduce(clone.token.inner, function(acc, t) {
if (t && t.isTermTree) {
push.apply(acc, t.destruct(context, options));
return acc;
}
acc.push(t);
return acc;
}, []);
acc.push(clone);
return acc;
} else if (Array.isArray(self[prop])) {
var destArr = _.reduce(self[prop], function(acc, t) {
if (t && t.isTermTree) {
push.apply(acc, t.destruct(context, options));
return acc;
}
acc.push(t);
return acc;
}, []);
push.apply(acc, destArr);
return acc;
} else if (self[prop]) {
acc.push(self[prop]);
return acc;
} else {
return acc;
}
}, []);
}
addDefCtx(def) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.addDefCtx(def);
});
} else if (self[prop]) {
self[prop] = self[prop].addDefCtx(def);
}
});
return this;
}
rename(id, name, phase) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.rename(id, name, phase);
});
} else if (self[prop]) {
self[prop] = self[prop].rename(id, name, phase);
}
});
return this;
}
imported(id, name, phase) {
var self = this;
_.each(this.constructor.properties, function(prop) {
if (Array.isArray(self[prop])) {
self[prop] = _.map(self[prop], function (item) {
return item.imported(id, name, phase);
});
} else if (self[prop]) {
self[prop] = self[prop].imported(id, name, phase);
}
});
return this;
}
}
dataclass EOF (eof) extends TermTree;
dataclass Keyword (keyword) extends TermTree;
dataclass Punc (punc) extends TermTree;
dataclass Delimiter (delim) extends TermTree;
dataclass ModuleTerm () extends TermTree;
dataclass Module (name, lang, body, imports, exports)extends ModuleTerm;
dataclass Import (kw, names, fromkw, from) extends ModuleTerm;
dataclass ImportForMacros (names, from) extends ModuleTerm;
dataclass Export (kw, name) extends ModuleTerm;
dataclass CompileTimeTerm () extends TermTree;
dataclass LetMacro (name, body) extends CompileTimeTerm;
dataclass Macro (name, body) extends CompileTimeTerm;
dataclass AnonMacro (body) extends CompileTimeTerm;
dataclass OperatorDefinition (type, name, prec, assoc, body) extends CompileTimeTerm;
dataclass VariableDeclaration (ident, eq, init, comma) extends TermTree;
dataclass Statement () extends TermTree;
dataclass Empty () extends Statement;
dataclass CatchClause (keyword, params, body) extends Statement;
dataclass ForStatement (keyword, cond) extends Statement;
dataclass ReturnStatement (keyword, expr) extends Statement {
destruct(context, options) {
var expr = this.expr.destruct(context, options);
// need to adjust the line numbers to make sure that the expr
// starts on the same line as the return keyword. This might
// not be the case if an operator or infix macro perturbed the
// line numbers during expansion.
expr = adjustLineContext(expr, this.keyword.keyword);
return this.keyword.destruct(context, options).concat(expr);
}
}
dataclass Expr () extends Statement;
dataclass UnaryOp (op, expr) extends Expr;
dataclass PostfixOp (expr, op) extends Expr;
dataclass BinOp (left, op, right) extends Expr;
dataclass AssignmentExpression (left, op, right) extends Expr;
dataclass ConditionalExpression (cond, question, tru, colon, fls) extends Expr;
dataclass NamedFun (keyword, star, name, params, body) extends Expr;
dataclass AnonFun (keyword, star, params, body) extends Expr;
dataclass ArrowFun (params, arrow, body) extends Expr;
dataclass ObjDotGet (left, dot, right) extends Expr;
dataclass ObjGet (left, right) extends Expr;
dataclass Template (template) extends Expr;
dataclass Call (fun, args) extends Expr;
dataclass QuoteSyntax (stx) extends Expr {
destruct(context, options) {
var tempId = fresh();
context.templateMap.set(tempId, this.stx.token.inner);
return [syn.makeIdent("getTemplate", this.stx),
syn.makeDelim("()", [
syn.makeValue(tempId, this.stx)
], this.stx)];
}
}
dataclass PrimaryExpression () extends Expr;
dataclass ThisExpression (keyword) extends PrimaryExpression;
dataclass Lit (lit) extends PrimaryExpression;
dataclass Block (body) extends PrimaryExpression;
dataclass ArrayLiteral (array) extends PrimaryExpression;
dataclass Id (id) extends PrimaryExpression;
dataclass Partial () extends TermTree;
dataclass PartialOperation (stx, left) extends Partial;
dataclass PartialExpression (stx, left, combine) extends Partial;
dataclass BindingStatement(keyword, decls) extends Statement {
destruct(context, options) {
return this.keyword
.destruct(context, options)
.concat(_.reduce(this.decls, function(acc, decl) {
push.apply(acc, decl.destruct(context, options));
return acc;
}, []));
}
}
dataclass VariableStatement (keyword, decls) extends BindingStatement;
dataclass LetStatement (keyword, decls) extends BindingStatement;
dataclass ConstStatement (keyword, decls) extends BindingStatement;
dataclass ParenExpression(args, delim, commas) extends PrimaryExpression {
destruct(context, options) {
var commas = this.commas.slice();
cloned newtok <- this.delim.token;
var delim = syntaxFromToken(newtok, this.delim);
delim.token.inner = _.reduce(this.args, function(acc, term) {
assert(term && term.isTermTree,
"expecting term trees in destruct of ParenExpression");
push.apply(acc, term.destruct(context, options));
// add all commas except for the last one
if (commas.length > 0) {
acc.push(commas.shift());
}
return acc;
}, []);
return Delimiter.create(delim).destruct(context, options);
}
}
function stxIsUnaryOp(stx) {
var staticOperators = ["+", "-", "~", "!",
"delete", "void", "typeof", "yield", "new",
"++", "--"];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function stxIsBinOp(stx) {
var staticOperators = ["+", "-", "*", "/", "%", "||", "&&", "|", "&", "^",
"==", "!=", "===", "!==",
"<", ">", "<=", ">=", "in", "instanceof",
"<<", ">>", ">>>"];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function getUnaryOpPrec(op) {
var operatorPrecedence = {
"new": 16,
"++": 15,
"--": 15,
"!": 14,
"~": 14,
"+": 14,
"-": 14,
"typeof": 14,
"void": 14,
"delete": 14,
"yield": 2
}
return operatorPrecedence[op];
}
function getBinaryOpPrec(op) {
var operatorPrecedence = {
"*": 13,
"/": 13,
"%": 13,
"+": 12,
"-": 12,
">>": 11,
"<<": 11,
">>>": 11,
"<": 10,
"<=": 10,
">": 10,
">=": 10,
"in": 10,
"instanceof": 10,
"==": 9,
"!=": 9,
"===": 9,
"!==": 9,
"&": 8,
"^": 7,
"|": 6,
"&&": 5,
"||":4
}
return operatorPrecedence[op];
}
function getBinaryOpAssoc(op) {
var operatorAssoc = {
"*": "left",
"/": "left",
"%": "left",
"+": "left",
"-": "left",
">>": "left",
"<<": "left",
">>>": "left",
"<": "left",
"<=": "left",
">": "left",
">=": "left",
"in": "left",
"instanceof": "left",
"==": "left",
"!=": "left",
"===": "left",
"!==": "left",
"&": "left",
"^": "left",
"|": "left",
"&&": "left",
"||": "left"
}
return operatorAssoc[op];
}
function stxIsAssignOp(stx) {
var staticOperators = ["=", "+=", "-=", "*=", "/=", "%=",
"<<=", ">>=", ">>>=",
"|=", "^=", "&="];
return _.contains(staticOperators, unwrapSyntax(stx));
}
function enforestVarStatement(stx, context, varStx) {
var decls = [];
var rest = stx;
var rhs;
if (!rest.length) {
throwSyntaxError("enforest", "Unexpected end of input", varStx);
}
if(expandCount >= maxExpands) {
return null;
}
while (rest.length) {
if (rest[0].token.type === parser.Token.Identifier) {
if (rest[1] && rest[1].token.type === parser.Token.Punctuator &&
rest[1].token.value === "=") {
rhs = get_expression(rest.slice(2), context);
if (rhs.result == null) {
throwSyntaxError("enforest", "Unexpected token", rhs.rest[0]);
}
if (rhs.rest[0] && rhs.rest[0].token.type === parser.Token.Punctuator &&
rhs.rest[0].token.value === ",") {
decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, rhs.rest[0]));
rest = rhs.rest.slice(1);
continue;
} else {
decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, null));
rest = rhs.rest;
break;
}
} else if (rest[1] && rest[1].token.type === parser.Token.Punctuator &&
rest[1].token.value === ",") {
decls.push(VariableDeclaration.create(rest[0], null, null, rest[1]));
rest = rest.slice(2);
} else {
decls.push(VariableDeclaration.create(rest[0], null, null, null));
rest = rest.slice(1);
break;
}
} else {
throwSyntaxError("enforest", "Unexpected token", rest[0]);
}
}
return {
result: decls,
rest: rest
}
}
function enforestAssignment(stx, context, left, prevStx, prevTerms) {
var op = stx[0];
var rightStx = stx.slice(1);
var opTerm = Punc.create(stx[0]);
var opPrevStx = tagWithTerm(opTerm, [stx[0]])
.concat(tagWithTerm(left, left.destruct(context).reverse()),
prevStx);
var opPrevTerms = [opTerm, left].concat(prevTerms);
var opRes = enforest(rightStx, context, opPrevStx, opPrevTerms);
if (opRes.result) {
// Lookbehind was matched, so it may not even be a binop anymore.
if (opRes.prevTerms.length < opPrevTerms.length) {
return opRes;
}
var right = opRes.result;
// only a binop if the right is a real expression
// so 2+2++ will only match 2+2
if (right.isExpr) {
var term = AssignmentExpression.create(left, op, right);
return {
result: term,
rest: opRes.rest,
prevStx: prevStx,
prevTerms: prevTerms
};
}
} else {
return opRes;
}
}
function enforestParenExpression(parens, context) {
var argRes, enforestedArgs = [], commas = [];
var innerTokens = parens.token.inner;
while (innerTokens.length > 0) {
argRes = enforest(innerTokens, context);
if (!argRes.result || !argRes.result.isExpr) {
return null;
}
enforestedArgs.push(argRes.result);
innerTokens = argRes.rest;
if (innerTokens[0] && innerTokens[0].token.value === ",") {
// record the comma for later
commas.push(innerTokens[0]);
// but dump it for the next loop turn
innerTokens = innerTokens.slice(1);
} else {
// either there are no more tokens or
// they aren't a comma, either way we
// are done with the loop
break;
}
}
return innerTokens.length ? null : ParenExpression.create(enforestedArgs, parens, commas);
}
function adjustLineContext(stx, original, current) {
// short circuit when the array is empty;
if (stx.length === 0) {
return stx;
}
current = current || {
lastLineNumber: stx[0].token.lineNumber || stx[0].token.startLineNumber,
lineNumber: original.token.lineNumber
};
return _.map(stx, function(stx) {
if (stx.token.type === parser.Token.Delimiter) {
// handle tokens with missing line info
stx.token.startLineNumber = typeof stx.token.startLineNumber == 'undefined'
? original.token.lineNumber
: stx.token.startLineNumber
stx.token.endLineNumber = typeof stx.token.endLineNumber == 'undefined'
? original.token.lineNumber
: stx.token.endLineNumber
stx.token.startLineStart = typeof stx.token.startLineStart == 'undefined'
? original.token.lineStart
: stx.token.startLineStart
stx.token.endLineStart = typeof stx.token.endLineStart == 'undefined'
? original.token.lineStart
: stx.token.endLineStart
stx.token.startRange = typeof stx.token.startRange == 'undefined'
? original.token.range
: stx.token.startRange
stx.token.endRange = typeof stx.token.endRange == 'undefined'
? original.token.range
: stx.token.endRange
stx.token.sm_startLineNumber = typeof stx.token.sm_startLineNumber == 'undefined'
? stx.token.startLineNumber
: stx.token.sm_startLineNumber;
stx.token.sm_endLineNumber = typeof stx.token.sm_endLineNumber == 'undefined'
? stx.token.endLineNumber
: stx.token.sm_endLineNumber;
stx.token.sm_startLineStart = typeof stx.token.sm_startLineStart == 'undefined'
? stx.token.startLineStart
: stx.token.sm_startLineStart;
stx.token.sm_endLineStart = typeof stx.token.sm_endLineStart == 'undefined'
? stx.token.endLineStart
: stx.token.sm_endLineStart;
stx.token.sm_startRange = typeof stx.token.sm_startRange == 'undefined'
? stx.token.startRange
: stx.token.sm_startRange;
stx.token.sm_endRange = typeof stx.token.sm_endRange == 'undefined'
? stx.token.endRange
: stx.token.sm_endRange;
if (stx.token.startLineNumber !== current.lineNumber) {
if (stx.token.startLineNumber !== current.lastLineNumber) {
current.lineNumber++;
current.lastLineNumber = stx.token.startLineNumber;
stx.token.startLineNumber = current.lineNumber;
} else {
current.lastLineNumber = stx.token.startLineNumber;
stx.token.startLineNumber = current.lineNumber;
}
}
return stx;
}
// handle tokens with missing line info
stx.token.lineNumber = typeof stx.token.lineNumber == 'undefined'
? original.token.lineNumber
: stx.token.lineNumber;
stx.token.lineStart = typeof stx.token.lineStart == 'undefined'
? original.token.lineStart
: stx.token.lineStart;
stx.token.range = typeof stx.token.range == 'undefined'
? original.token.range
: stx.token.range;
// Only set the sourcemap line info once. Necessary because a single
// syntax object can go through expansion multiple times. If at some point
// we want to write an expansion stepper this might be a good place to store
// intermediate expansion line info (ie push to a stack instead of
// just write once).
stx.token.sm_lineNumber = typeof stx.token.sm_lineNumber == 'undefined'
? stx.token.lineNumber
: stx.token.sm_lineNumber;
stx.token.sm_lineStart = typeof stx.token.sm_lineStart == 'undefined'
? stx.token.lineStart
: stx.token.sm_lineStart;
stx.token.sm_range = typeof stx.token.sm_range == 'undefined'
? stx.token.range.slice()
: stx.token.sm_range;
// move the line info to line up with the macro name
// (line info starting from the macro name)
if (stx.token.lineNumber !== current.lineNumber) {
if (stx.token.lineNumber !== current.lastLineNumber) {
current.lineNumber++;
current.lastLineNumber = stx.token.lineNumber;
stx.token.lineNumber = current.lineNumber;
} else {
current.lastLineNumber = stx.token.lineNumber;
stx.token.lineNumber = current.lineNumber;
}
}
return stx;
});
}
function getName(head, rest) {
var idx = 0;
var curr = head;
var next = rest[idx];
var name = [head];
while (true) {
if (next &&
(next.token.type === parser.Token.Punctuator ||
next.token.type === parser.Token.Identifier ||
next.token.type === parser.Token.Keyword) &&
(toksAdjacent(curr, next))) {
name.push(next);
curr = next;
next = rest[++idx];
} else {
return name;
}
}
}
function getValueInEnv(head, rest, context, phase) {
if (!(head.token.type === parser.Token.Identifier ||
head.token.type === parser.Token.Keyword ||
head.token.type === parser.Token.Punctuator)) {
return null;
}
var name = getName(head, rest);
// simple case, don't need to create a new syntax object
if (name.length === 1) {
if (context.env.names.get(unwrapSyntax(name[0]))) {
var resolvedName = resolve(name[0], phase);
if (context.env.has(resolvedName)) {
return context.env.get(resolvedName);
}
}
return null;
} else {
while (name.length > 0) {
var nameStr = name.map(unwrapSyntax).join("");
if (context.env.names.get(nameStr)) {
var nameStx = syn.makeIdent(nameStr, name[0]);
var resolvedName = resolve(nameStx, phase);
if (context.env.has(resolvedName)) {
return context.env.get(resolvedName);
}
}
name.pop();
}
return null;
}
}
function nameInEnv(head, rest, context, phase) {
return getValueInEnv(head, rest, context, phase) !== null;
}
// This should only be used on things that can't be rebound except by
// macros (puncs, keywords).
function resolveFast(stx, env, phase) {
var name = unwrapSyntax(stx);
return env.names.get(name) ? resolve(stx, phase) : name;
}
function expandMacro(stx, context, opCtx, opType, macroObj) {
// pull the macro transformer out the environment
var head = stx[0];
var rest = stx.slice(1);
macroObj = macroObj || getValueInEnv(head, rest, context, context.phase);
var stxArg = rest.slice(macroObj.fullName.length - 1);
var transformer;
if (opType != null) {
assert(opType === "binary" || opType === "unary", "operator type should be either unary or binary: " + opType);
transformer = macroObj[opType].fn;
} else {
transformer = macroObj.fn;
}
assert(typeof transformer === "function", "Macro transformer not bound for: "
+ head.token.value);
// create a new mark to be used for the input to
// the macro
var newMark = fresh();
var transformerContext = makeExpanderContext(_.defaults({mark: newMark}, context));
// apply the transformer
var rt;
try {
rt = transformer([head].concat(stxArg),
transformerContext,
opCtx.prevStx,
opCtx.prevTerms);
} catch (e) {
if (e instanceof SyntaxCaseError) {
// add a nicer error for syntax case
var nameStr = macroObj.fullName.map(function(stx) {
return stx.token.value;
}).join("");
if (opType != null) {
var argumentString = "`" + stxArg.slice(0, 5).map(function(stx) {
return stx.token.value;
}).join(" ") + "...`";
throwSyntaxError("operator", "Operator `" + nameStr +
"` could not be matched with " +
argumentString,
head);
} else {
var argumentString = "`" + stxArg.slice(0, 5).map(function(stx) {
return stx.token.value;
}).join(" ") + "...`";
throwSyntaxError("macro", "Macro `" + nameStr +
"` could not be matched with " +
argumentString,
head);
}
}
else {
// just rethrow it
throw e;
}
}
if (!builtinMode && !macroObj.builtin) {
expandCount++;
}
if(!Array.isArray(rt.result)) {
throwSyntaxError("enforest", "Macro must return a syntax array", stx[0]);
}
if(rt.result.length > 0) {
var adjustedResult = adjustLineContext(rt.result, head);
if (stx[0].token.leadingComments) {
if (adjustedResult[0].token.leadingComments) {
adjustedResult[0].token.leadingComments = adjustedResult[0].token.leadingComments.concat(head.token.leadingComments);
} else {
adjustedResult[0].token.leadingComments = head.token.leadingComments;
}
}
rt.result = adjustedResult;
}
return rt;
}
function comparePrec(left, right, assoc) {
if (assoc === "left") {
return left <= right;
}
return left < right;
}
// @ (SyntaxObject, SyntaxObject) -> Bool
function toksAdjacent(a, b) {
var arange = a.token.sm_range || a.token.range || a.token.endRange;
var brange = b.token.sm_range || b.token.range || b.token.endRange;
return arange && brange && arange[1] === brange[0];
}
// @ (SyntaxObject, SyntaxObject) -> Bool
function syntaxInnerValuesEq(synA, synB) {
var a = synA.token.inner, b = synB.token.inner;
return a.length === b.length &&
_.zip(a, b) |> ziped -> _.all(ziped, pair -> {
return unwrapSyntax(pair[0]) === unwrapSyntax(pair[1]);
});
}
// enforest the tokens, returns an object with the `result` TermTree and
// the uninterpreted `rest` of the syntax
// @ ([...SyntaxObject], ExpanderContext) -> {
// result: Null or TermTreeObject,
// rest: [...SyntaxObject]
// }
function enforest(toks, context, prevStx, prevTerms) {
assert(toks.length > 0, "enforest assumes there are tokens to work with");
prevStx = prevStx || [];
prevTerms = prevTerms || [];
if(expandCount >= maxExpands) {
return { result: null,
rest: toks };
}
function step(head, rest, opCtx) {
var innerTokens;
assert(Array.isArray(rest), "result must at least be an empty array");
if (head.isTermTree) {
var isCustomOp = false;
var uopMacroObj;
var uopSyntax;
if (head.isPunc || head.isKeyword || head.isId) {
if (head.isPunc) {
uopSyntax = head.punc;
} else if (head.isKeyword) {
uopSyntax = head.keyword;
} else if (head.isId) {
uopSyntax = head.id;
}
uopMacroObj = getValueInEnv(uopSyntax, rest, context, context.phase);
isCustomOp = uopMacroObj && uopMacroObj.isOp;
}
// look up once (we want to check multiple properties on bopMacroObj
// without repeatedly calling getValueInEnv)
var bopMacroObj;
if (rest[0] && rest[1]) {
bopMacroObj = getValueInEnv(rest[0], rest.slice(1), context, context.phase);
}
// unary operator
if ((isCustomOp && uopMacroObj.unary) || (uopSyntax && stxIsUnaryOp(uopSyntax))) {
var uopPrec;
if (isCustomOp && uopMacroObj.unary) {
uopPrec = uopMacroObj.unary.prec;
} else {
uopPrec = getUnaryOpPrec(unwrapSyntax(uopSyntax));
}
var opRest = rest;
var uopMacroName;
if (uopMacroObj) {
uopMacroName = [uopSyntax].concat(rest.slice(0, uopMacroObj.fullName.length - 1));
opRest = rest.slice(uopMacroObj.fullName.length - 1);
}
var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var unopTerm = PartialOperation.create(head, leftLeft);
var unopPrevStx = tagWithTerm(unopTerm, head.destruct(context).reverse()).concat(opCtx.prevStx);
var unopPrevTerms = [unopTerm].concat(opCtx.prevTerms);
var unopOpCtx = _.extend({}, opCtx, {
combine: function(t) {
if (t.isExpr) {
if (isCustomOp && uopMacroObj.unary) {
var rt = expandMacro(uopMacroName.concat(t.destruct(context)), context, opCtx, "unary");
var newt = get_expression(rt.result, context);
assert(newt.rest.length === 0, "should never have left over syntax");
return opCtx.combine(newt.result);
}
return opCtx.combine(UnaryOp.create(uopSyntax, t));
} else {
// not actually an expression so don't create
// a UnaryOp term just return with the punctuator
return opCtx.combine(head);
}
},
prec: uopPrec,
prevStx: unopPrevStx,
prevTerms: unopPrevTerms,
op: unopTerm
});
return step(opRest[0], opRest.slice(1), unopOpCtx);
// BinOp
} else if (head.isExpr &&
(rest[0] && rest[1] &&
((stxIsBinOp(rest[0]) && !bopMacroObj) ||
(bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary)))) {
var opRes;
var op = rest[0];
var left = head;
var rightStx = rest.slice(1);
var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var leftTerm = PartialExpression.create(head.destruct(context), leftLeft, function() {
return step(head, [], opCtx);
});
var opTerm = PartialOperation.create(op, leftTerm);
var opPrevStx = tagWithTerm(opTerm, [rest[0]])
.concat(tagWithTerm(leftTerm, head.destruct(context)).reverse(),
opCtx.prevStx);
var opPrevTerms = [opTerm, leftTerm].concat(opCtx.prevTerms);
var isCustomOp = bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary;
var bopPrec;
var bopAssoc;
if (isCustomOp && bopMacroObj.binary) {
bopPrec = bopMacroObj.binary.prec;
bopAssoc = bopMacroObj.binary.assoc;
} else {
bopPrec = getBinaryOpPrec(unwrapSyntax(op));
bopAssoc = getBinaryOpAssoc(unwrapSyntax(op));
}
assert(bopPrec !== undefined, "expecting a precedence for operator: " + op);
var newStack;
if (comparePrec(bopPrec, opCtx.prec, bopAssoc)) {
var bopCtx = opCtx;
var combResult = opCtx.combine(head);
if (opCtx.stack.length > 0) {
return step(combResult.term, rest, opCtx.stack[0]);
}
left = combResult.term;
newStack = opCtx.stack;
opPrevStx = combResult.prevStx;
opPrevTerms = combResult.prevTerms;
} else {
newStack = [opCtx].concat(opCtx.stack);
}
assert(opCtx.combine !== undefined,
"expecting a combine function");
var opRightStx = rightStx;
var bopMacroName;
if (isCustomOp) {
bopMacroName = rest.slice(0, bopMacroObj.fullName.length);
opRightStx = rightStx.slice(bopMacroObj.fullName.length - 1);
}
var bopOpCtx = _.extend({}, opCtx, {
combine: function(right) {
if (right.isExpr) {
if (isCustomOp && bopMacroObj.binary) {
var leftStx = left.destruct(context);
var rightStx = right.destruct(context);
var rt = expandMacro(bopMacroName.concat(syn.makeDelim("()", leftStx, leftStx[0]),
syn.makeDelim("()", rightStx, rightStx[0])),
context, opCtx, "binary");
var newt = get_expression(rt.result, context);
assert(newt.rest.length === 0, "should never have left over syntax");
return {
term: newt.result,
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
}
return {
term: BinOp.create(left, op, right),
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
} else {
return {
term: head,
prevStx: opPrevStx,
prevTerms: opPrevTerms
};
}
},
prec: bopPrec,
op: opTerm,
stack: newStack,
prevStx: opPrevStx,
prevTerms: opPrevTerms,
});
return step(opRightStx[0], opRightStx.slice(1), bopOpCtx);
// Call
} else if (head.isExpr && (rest[0] &&
rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()")) {
var parenRes = enforestParenExpression(rest[0], context);
if (parenRes) {
return step(Call.create(head, parenRes),
rest.slice(1),
opCtx);
}
// Conditional ( x ? true : false)
} else if (head.isExpr &&
(rest[0] && resolveFast(rest[0], context.env, context.phase) === "?")) {
var question = rest[0];
var condRes = enforest(rest.slice(1), context);
if (condRes.result) {
var truExpr = condRes.result;
var condRight = condRes.rest;
if (truExpr.isExpr &&
condRight[0] && resolveFast(condRight[0], context.env, context.phase) === ":") {
var colon = condRight[0];
var flsRes = enforest(condRight.slice(1), context);
var flsExpr = flsRes.result;
if (flsExpr.isExpr) {
// operators are combined before the ternary
if (opCtx.prec >= 4) { // ternary is like a operator with prec 4
var headResult = opCtx.combine(head);
var condTerm = ConditionalExpression.create(headResult.term,
question,
truExpr,
colon,
flsExpr);
if (opCtx.stack.length > 0) {
return step(condTerm,
flsRes.rest,
opCtx.stack[0]);
} else {
return {
result: condTerm,
rest: flsRes.rest,
prevStx: headResult.prevStx,
prevTerms: headResult.prevTerms
};
}
} else {
var condTerm = ConditionalExpression.create(head,
question,
truExpr,
colon,
flsExpr);
return step(condTerm,
flsRes.rest,
opCtx);
}
}
}
}
// Arrow functions with expression bodies
} else if (head.isDelimiter &&
head.delim.token.value === "()" &&
rest[0] &&
rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>") {
var arrowRes = enforest(rest.slice(1), context);
if (arrowRes.result && arrowRes.result.isExpr) {
return step(ArrowFun.create(head.delim,
rest[0],
arrowRes.result.destruct(context)),
arrowRes.rest,
opCtx);
} else {
throwSyntaxError("enforest",
"Body of arrow function must be an expression",
rest.slice(1));
}
// Arrow functions with expression bodies
} else if (head.isId &&
rest[0] &&
rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>") {
var res = enforest(rest.slice(1), context);
if (res.result && res.result.isExpr) {
return step(ArrowFun.create(head.id,
rest[0],
res.result.destruct(context)),
res.rest,
opCtx);
} else {
throwSyntaxError("enforest",
"Body of arrow function must be an expression",
rest.slice(1));
}
// ParenExpr
} else if (head.isDelimiter &&
head.delim.token.value === "()") {
// empty parens are acceptable but enforest
// doesn't accept empty arrays so short
// circuit here
if (head.delim.token.inner.length === 0) {
return step(ParenExpression.create([Empty.create()], head.delim, []),
rest,
opCtx);
} else {
var parenRes = enforestParenExpression(head.delim, context);
if (parenRes) {
return step(parenRes, rest, opCtx);
}
}
// AssignmentExpression
} else if (head.isExpr &&
((head.isId ||
head.isObjGet ||
head.isObjDotGet ||
head.isThisExpression) &&
rest[0] && rest[1] && !bopMacroObj && stxIsAssignOp(rest[0]))) {
var opRes = enforestAssignment(rest, context, head, prevStx, prevTerms);
if(opRes && opRes.result) {
return step(opRes.result, opRes.rest, _.extend({}, opCtx, {
prevStx: opRes.prevStx,
prevTerms: opRes.prevTerms
}));
}
// Postfix
} else if(head.isExpr &&
(rest[0] && (unwrapSyntax(rest[0]) === "++" ||
unwrapSyntax(rest[0]) === "--"))) {
// Check if the operator is a macro first.
if (context.env.has(resolveFast(rest[0], context.env, context.phase))) {
var headStx = tagWithTerm(head, head.destruct(context).reverse());
var opPrevStx = headStx.concat(prevStx);
var opPrevTerms = [head].concat(prevTerms);
var opRes = enforest(rest, context, opPrevStx, opPrevTerms);
if (opRes.prevTerms.length < opPrevTerms.length) {
return opRes;
} else if(opRes.result) {
return step(head,
opRes.result.destruct(context).concat(opRes.rest),
opCtx);
}
}
return step(PostfixOp.create(head, rest[0]),
rest.slice(1),
opCtx);
// ObjectGet (computed)
} else if(head.isExpr &&
(rest[0] && rest[0].token.value === "[]")) {
return step(ObjGet.create(head, Delimiter.create(rest[0])),
rest.slice(1),
opCtx);
// ObjectGet
} else if (head.isExpr &&
(rest[0] && unwrapSyntax(rest[0]) === "." &&
!context.env.has(resolveFast(rest[0], context.env, context.phase)) &&
rest[1] &&
(rest[1].token.type === parser.Token.Identifier ||
rest[1].token.type === parser.Token.Keyword))) {
// Check if the identifier is a macro first.
if (context.env.has(resolveFast(rest[1], context.env, context.phase))) {
var headStx = tagWithTerm(head, head.destruct(context).reverse());
var dotTerm = Punc.create(rest[0]);
var dotTerms = [dotTerm].concat(head, prevTerms);
var dotStx = tagWithTerm(dotTerm, [rest[0]]).concat(headStx, prevStx);
var dotRes = enforest(rest.slice(1), context, dotStx, dotTerms);
if (dotRes.prevTerms.length < dotTerms.length) {
return dotRes;
} else if(dotRes.result) {
return step(head,
[rest[0]].concat(dotRes.result.destruct(context), dotRes.rest),
opCtx);
}
}
return step(ObjDotGet.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// ArrayLiteral
} else if (head.isDelimiter &&
head.delim.token.value === "[]") {
return step(ArrayLiteral.create(head), rest, opCtx);
// Block
} else if (head.isDelimiter &&
head.delim.token.value === "{}") {
return step(Block.create(head), rest, opCtx);
// quote syntax
} else if (head.isId &&
unwrapSyntax(head.id) === "#quoteSyntax" &&
rest[0] && rest[0].token.value === "{}") {
return step(QuoteSyntax.create(rest[0]), rest.slice(1), opCtx);
// return statement
} else if (head.isKeyword && unwrapSyntax(head.keyword) === "return") {
if (rest[0] && rest[0].token.lineNumber === head.keyword.token.lineNumber) {
var returnPrevStx = tagWithTerm(head,
head.destruct(context)).concat(opCtx.prevStx);
var returnPrevTerms = [head].concat(opCtx.prevTerms);
var returnExpr = enforest(rest, context, returnPrevStx, returnPrevTerms);
if (returnExpr.prevTerms.length < opCtx.prevTerms.length) {
return returnExpr;
}
if (returnExpr.result.isExpr) {
return step(ReturnStatement.create(head, returnExpr.result),
returnExpr.rest,
opCtx);
}
} else {
return step(ReturnStatement.create(head, Empty.create()),
rest,
opCtx);
}
// let statements
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "let") {
var nameTokens = [];
if (rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()") {
nameTokens = rest[0].token.inner;
} else {
nameTokens.push(rest[0]);
}
// Let macro
if (rest[1] && rest[1].token.value === "=" &&
rest[2] && rest[2].token.value === "macro") {
var mac = enforest(rest.slice(2), context);
if(mac.result) {
if (!mac.result.isAnonMacro) {
throwSyntaxError("enforest", "expecting an anonymous macro definition in syntax let binding", rest.slice(2));
}
return step(LetMacro.create(nameTokens, mac.result.body),
mac.rest,
opCtx);
}
// Let statement
} else {
var lsRes = enforestVarStatement(rest, context, head.keyword);
if (lsRes && lsRes.result) {
return step(LetStatement.create(head, lsRes.result),
lsRes.rest,
opCtx);
}
}
// VariableStatement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "var" && rest[0]) {
var vsRes = enforestVarStatement(rest, context, head.keyword);
if (vsRes && vsRes.result) {
return step(VariableStatement.create(head, vsRes.result),
vsRes.rest,
opCtx);
}
// Const Statement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "const" && rest[0]) {
var csRes = enforestVarStatement(rest, context, head.keyword);
if (csRes && csRes.result) {
return step(ConstStatement.create(head, csRes.result),
csRes.rest,
opCtx);
}
// for statement
} else if (head.isKeyword &&
unwrapSyntax(head.keyword) === "for" &&
rest[0] && rest[0].token.value === "()") {
return step(ForStatement.create(head.keyword, rest[0]),
rest.slice(1),
opCtx);
}
} else {
assert(head && head.token, "assuming head is a syntax object");
var macroObj = expandCount < maxExpands && getValueInEnv(head, rest, context, context.phase);
// macro invocation
if (macroObj && typeof macroObj.fn === "function" && !macroObj.isOp) {
var rt = expandMacro([head].concat(rest), context, opCtx, null, macroObj);
var newOpCtx = opCtx;
if (rt.prevTerms && rt.prevTerms.length < opCtx.prevTerms.length) {
newOpCtx = rewindOpCtx(opCtx, rt);
}
if (rt.result.length > 0) {
return step(rt.result[0],
rt.result.slice(1).concat(rt.rest),
newOpCtx);
} else {
return step(Empty.create(), rt.rest, newOpCtx);
}
// anon macro definition
} else if (head.token.type === parser.Token.Identifier &&
unwrapSyntax(head) === "macro" &&
resolve(head, context.phase) === "macro" &&
rest[0] && rest[0].token.value === "{}") {
return step(AnonMacro.create(rest[0].token.inner),
rest.slice(1),
opCtx);
// macro definition
} else if (head.token.type === parser.Token.Identifier &&
unwrapSyntax(head) === "macro" &&
resolve(head, context.phase) === "macro") {
var nameTokens = [];
if (rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()") {
nameTokens = rest[0].token.inner;
} else {
nameTokens.push(rest[0])
}
if (rest[1] && rest[1].token.type === parser.Token.Delimiter) {
return step(Macro.create(nameTokens, rest[1].token.inner),
rest.slice(2),
opCtx);
} else {
throwSyntaxError("enforest", "Macro declaration must include body", rest[1]);
}
// operator definition
// unaryop (neg) 1 { macro { rule { $op:expr } => { $op } } }
} else if (head.token.type === parser.Token.Identifier &&
head.token.value === "unaryop" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.NumericLiteral &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2] && rest[2].token.value === "{}") {
var trans = enforest(rest[2].token.inner, context);
return step(OperatorDefinition.create(syn.makeValue("unary", head),
rest[0].token.inner,
rest[1],
null,
trans.result.body),
rest.slice(3),
opCtx);
// operator definition
// binaryop (neg) 1 left { macro { rule { $op:expr } => { $op } } }
} else if (head.token.type === parser.Token.Identifier &&
head.token.value === "binaryop" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.NumericLiteral &&
rest[2] && rest[2].token.type === parser.Token.Identifier &&
rest[3] && rest[3].token.type === parser.Token.Delimiter &&
rest[3] && rest[3].token.value === "{}") {
var trans = enforest(rest[3].token.inner, context);
return step(OperatorDefinition.create(syn.makeValue("binary", head),
rest[0].token.inner,
rest[1],
rest[2],
trans.result.body),
rest.slice(4),
opCtx);
// function definition
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Identifier &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "()" &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "{}") {
rest[1].token.inner = rest[1].token.inner;
rest[2].token.inner = rest[2].token.inner;
return step(NamedFun.create(head, null, rest[0],
rest[1],
rest[2]),
rest.slice(3),
opCtx);
// generator function definition
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
rest[0].token.value === "*" &&
rest[1] && rest[1].token.type === parser.Token.Identifier &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "()" &&
rest[3] && rest[3].token.type === parser.Token.Delimiter &&
rest[3].token.value === "{}") {
rest[2].token.inner = rest[2].token.inner;
rest[3].token.inner = rest[3].token.inner;
return step(NamedFun.create(head, rest[0], rest[1],
rest[2],
rest[3]),
rest.slice(4),
opCtx);
// anonymous function definition
} else if(head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
rest[0].token.inner = rest[0].token.inner;
rest[1].token.inner = rest[1].token.inner;
return step(AnonFun.create(head,
null,
rest[0],
rest[1]),
rest.slice(2),
opCtx);
// anonymous generator function definition
} else if(head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "function" &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
rest[0].token.value === "*" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "()" &&
rest[2] && rest[2].token.type === parser.Token.Delimiter &&
rest[2].token.value === "{}") {
rest[1].token.inner = rest[1].token.inner;
rest[2].token.inner = rest[2].token.inner;
return step(AnonFun.create(head,
rest[0],
rest[1],
rest[2]),
rest.slice(3),
opCtx);
// arrow function
} else if(((head.token.type === parser.Token.Delimiter &&
head.token.value === "()") ||
head.token.type === parser.Token.Identifier) &&
rest[0] && rest[0].token.type === parser.Token.Punctuator &&
resolveFast(rest[0], context.env, context.phase) === "=>" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
return step(ArrowFun.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// catch statement
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "catch" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "()" &&
rest[1] && rest[1].token.type === parser.Token.Delimiter &&
rest[1].token.value === "{}") {
rest[0].token.inner = rest[0].token.inner;
rest[1].token.inner = rest[1].token.inner;
return step(CatchClause.create(head, rest[0], rest[1]),
rest.slice(2),
opCtx);
// this expression
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "this") {
return step(ThisExpression.create(head), rest, opCtx);
// literal
} else if (head.token.type === parser.Token.NumericLiteral ||
head.token.type === parser.Token.StringLiteral ||
head.token.type === parser.Token.BooleanLiteral ||
head.token.type === parser.Token.RegularExpression ||
head.token.type === parser.Token.NullLiteral) {
return step(Lit.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "import" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "{}" &&
rest[1] && unwrapSyntax(rest[1]) === "from" &&
rest[2] && rest[2].token.type === parser.Token.StringLiteral &&
rest[3] && unwrapSyntax(rest[3]) === "for" &&
rest[4] && unwrapSyntax(rest[4]) === "macros") {
var importRest;
if (rest[5] && rest[5].token.type === parser.Token.Punctuator &&
rest[5].token.value === ";") {
importRest = rest.slice(6);
} else {
importRest = rest.slice(5);
}
return step(ImportForMacros.create(rest[0], rest[2]), importRest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "import" &&
rest[0] && rest[0].token.type === parser.Token.Delimiter &&
rest[0].token.value === "{}" &&
rest[1] && unwrapSyntax(rest[1]) === "from" &&
rest[2] && rest[2].token.type === parser.Token.StringLiteral) {
var importRest;
if (rest[3] && rest[3].token.type === parser.Token.Punctuator &&
rest[3].token.value === ";") {
importRest = rest.slice(4);
} else {
importRest = rest.slice(3);
}
return step(Import.create(head, rest[0], rest[1], rest[2]), importRest, opCtx);
// export
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "export" &&
rest[0] && (rest[0].token.type === parser.Token.Identifier ||
rest[0].token.type === parser.Token.Keyword ||
rest[0].token.type === parser.Token.Punctuator ||
rest[0].token.type === parser.Token.Delimiter)) {
if (unwrapSyntax(rest[1]) !== ";" && toksAdjacent(rest[0], rest[1])) {
throwSyntaxError("enforest",
"multi-token macro/operator names must be wrapped in () when exporting",
rest[1]);
}
return step(Export.create(head, rest[0]), rest.slice(1), opCtx);
// identifier
} else if (head.token.type === parser.Token.Identifier) {
return step(Id.create(head), rest, opCtx);
// punctuator
} else if (head.token.type === parser.Token.Punctuator) {
return step(Punc.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Keyword &&
unwrapSyntax(head) === "with") {
throwSyntaxError("enforest", "with is not supported in sweet.js", head);
// keyword
} else if (head.token.type === parser.Token.Keyword) {
return step(Keyword.create(head), rest, opCtx);
// Delimiter
} else if (head.token.type === parser.Token.Delimiter) {
return step(Delimiter.create(head), rest, opCtx);
} else if (head.token.type === parser.Token.Template) {
return step(Template.create(head), rest, opCtx);
// end of file
} else if (head.token.type === parser.Token.EOF) {
assert(rest.length === 0, "nothing should be after an EOF");
return step(EOF.create(head), [], opCtx);
} else {
// todo: are we missing cases?
assert(false, "not implemented");
}
}
// Potentially an infix macro
// This should only be invoked on runtime syntax terms
if (!head.isMacro && !head.isLetMacro && !head.isAnonMacro && !head.isOperatorDefinition &&
rest.length && nameInEnv(rest[0], rest.slice(1), context, context.phase) &&
getValueInEnv(rest[0], rest.slice(1), context, context.phase).isOp === false) {
var infLeftTerm = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial
? opCtx.prevTerms[0]
: null;
var infTerm = PartialExpression.create(head.destruct(context), infLeftTerm, function() {
return step(head, [], opCtx);
});
var infPrevStx = tagWithTerm(infTerm, head.destruct(context)).reverse().concat(opCtx.prevStx);
var infPrevTerms = [infTerm].concat(opCtx.prevTerms);
var infRes = expandMacro(rest, context, {
prevStx: infPrevStx,
prevTerms: infPrevTerms
});
if (infRes.prevTerms && infRes.prevTerms.length < infPrevTerms.length) {
var infOpCtx = rewindOpCtx(opCtx, infRes);
return step(infRes.result[0], infRes.result.slice(1).concat(infRes.rest), infOpCtx);
} else {
return step(head, infRes.result.concat(infRes.rest), opCtx);
}
}
// done with current step so combine and continue on
var combResult = opCtx.combine(head);
if (opCtx.stack.length === 0) {
return {
result: combResult.term,
rest: rest,
prevStx: combResult.prevStx,
prevTerms: combResult.prevTerms
};
} else {
return step(combResult.term, rest, opCtx.stack[0]);
}
}
return step(toks[0], toks.slice(1), {
combine: function(t) {
return {
term: t,
prevStx: prevStx,
prevTerms: prevTerms
};
},
prec: 0,
stack: [],
op: null,
prevStx: prevStx,
prevTerms: prevTerms
});
}
function rewindOpCtx(opCtx, res) {
// If we've consumed all pending operators, we can just start over.
// It's important that we always thread the new prevStx and prevTerms
// through, otherwise the old ones will still persist.
if (!res.prevTerms.length ||
!res.prevTerms[0].isPartial) {
return _.extend({}, opCtx, {
combine: function(t) {
return {
term: t,
prevStx: res.prevStx,
prevTerms: res.prevTerms
};
},
prec: 0,
op: null,
stack: [],
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
// To rewind, we need to find the first (previous) pending operator. It
// acts as a marker in the opCtx to let us know how far we need to go
// back.
var op = null;
for (var i = 0; i < res.prevTerms.length; i++) {
if (!res.prevTerms[i].isPartial) {
break;
}
if (res.prevTerms[i].isPartialOperation) {
op = res.prevTerms[i];
break;
}
}
// If the op matches the current opCtx, we don't need to rewind
// anything, but we still need to persist the prevStx and prevTerms.
if (opCtx.op === op) {
return _.extend({}, opCtx, {
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
for (var i = 0; i < opCtx.stack.length; i++) {
if (opCtx.stack[i].op === op) {
return _.extend({}, opCtx.stack[i], {
prevStx: res.prevStx,
prevTerms: res.prevTerms
});
}
}
assert(false, "Rewind failed.");
}
function get_expression(stx, context) {
if (stx[0].term) {
for (var termLen = 1; termLen < stx.length; termLen++) {
if (stx[termLen].term !== stx[0].term) {
break;
}
}
// Guard the termLen because we can have a multi-token term that
// we don't want to split. TODO: is there something we can do to
// get around this safely?
if (stx[0].term.isPartialExpression &&
termLen === stx[0].term.stx.length) {
var expr = stx[0].term.combine().result;
for (var i = 1, term = stx[0].term; i < stx.length; i++) {
if (stx[i].term !== term) {
if (term && term.isPartial) {
term = term.left;
i--;
} else {
break;
}
}
}
return {
result: expr,
rest: stx.slice(i)
};
} else if (stx[0].term.isExpr) {
return {
result: stx[0].term,
rest: stx.slice(termLen)
};
} else {
return {
result: null,
rest: stx
};
}
}
var res = enforest(stx, context);
if (!res.result || !res.result.isExpr) {
return {
result: null,
rest: stx
};
}
return res;
}
function tagWithTerm(term, stx) {
return stx.map(function(s) {
cloned newtok <- s.token;
s = syntaxFromToken(newtok, s);
s.term = term;
return s;
});
}
// mark each syntax object in the pattern environment,
// mutating the environment
function applyMarkToPatternEnv (newMark, env) {
/*
Takes a `match` object:
{
level: <num>,
match: [<match> or <syntax>]
}
where the match property is an array of syntax objects at the bottom (0) level.
Does a depth-first search and applys the mark to each syntax object.
*/
function dfs(match) {
if (match.level === 0) {
// replace the match property with the marked syntax
match.match = _.map(match.match, function(stx) {
return stx.mark(newMark);
});
} else {
_.each(match.match, function(match) {
dfs(match);
});
}
}
_.keys(env).forEach(function(key) {
dfs(env[key]);
});
}
// given the syntax for a macro, produce a macro transformer
// (Macro) -> (([...CSyntax]) -> ReadTree)
function loadMacroDef(body, context, phase) {
var expanded = body[0].destruct(context, {stripCompileTerm: true});
var stub = parser.read("()");
stub[0].token.inner = expanded;
var flattend = flatten(stub);
var bodyCode = codegen.generate(parser.parse(flattend, {phase: phase}));
var macroGlobal = {
makeValue: syn.makeValue,
makeRegex: syn.makeRegex,
makeIdent: syn.makeIdent,
makeKeyword: syn.makeKeyword,
makePunc: syn.makePunc,
makeDelim: syn.makeDelim,
filename: context.filename,
require: function(id) {
if (context.requireModule) {
return context.requireModule(id, context.filename);
}
return require(id);
},
getExpr: function(stx) {
var r;
if (stx.length === 0) {
return {
success: false,
result: [],
rest: []
};
}
r = get_expression(stx, context);
return {
success: r.result !== null,
result: r.result === null ? [] : r.result.destruct(context),
rest: r.rest
};
},
getIdent: function(stx) {
if (stx[0] && stx[0].token.type === parser.Token.Identifier) {
return {
success: true,
result: [stx[0]],
rest: stx.slice(1)
};
}
return {
success: false,
result: [],
rest: stx
};
},
getLit: function(stx) {
if (stx[0] && patternModule.typeIsLiteral(stx[0].token.type)) {
return {
success: true,
result: [stx[0]],
rest: stx.slice(1)
};
}
return {
success: false,
result: [],
rest: stx
};
},
unwrapSyntax: syn.unwrapSyntax,
throwSyntaxError: throwSyntaxError,
throwSyntaxCaseError: throwSyntaxCaseError,
prettyPrint: syn.prettyPrint,
parser: parser,
__fresh: fresh,
_: _,
patternModule: patternModule,
getPattern: function(id) {
return context.patternMap.get(id);
},
getTemplate: function(id) {
assert(context.templateMap.has(id), "missing template");
return syn.cloneSyntaxArray(context.templateMap.get(id));
},
applyMarkToPatternEnv: applyMarkToPatternEnv,
mergeMatches: function(newMatch, oldMatch) {
newMatch.patternEnv = _.extend({}, oldMatch.patternEnv, newMatch.patternEnv);
return newMatch;
},
console: console
};
context.env.keys().forEach(key -> {
var val = context.env.get(key);
// load the compile time values into the global object
if (val && val.value) {
macroGlobal[key] = val.value;
}
});
var macroFn;
if (vm) {
macroFn = vm.runInNewContext("(function() { return " + bodyCode + " })()",
macroGlobal);
} else {
macroFn = scopedEval(bodyCode, macroGlobal);
}
return macroFn;
}
// similar to `parse1` in the honu paper
// @ ([...SyntaxObject], ExpanderContext) -> {
// terms: [...TermTreeObject],
// context: ExpanderContext,
// restStx: Undefined or [...SyntaxObject]
// }
function expandToTermTree(stx, context) {
assert(context, "expander context is required");
var f, head, prevStx, restStx, prevTerms, macroDefinition;
var rest = stx;
while (rest.length > 0) {
assert(rest[0].token, "expecting a syntax object");
f = enforest(rest, context, prevStx, prevTerms);
// head :: TermTree
head = f.result;
// rest :: [Syntax]
rest = f.rest;
if (!head) {
// no head means the expansions stopped prematurely (for stepping)
restStx = rest;
break;
}
var destructed = tagWithTerm(head, f.result.destruct(context));
prevTerms = [head].concat(f.prevTerms);
prevStx = destructed.reverse().concat(f.prevStx);
if (head.isMacro && expandCount < maxExpands) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({},
context,
{phase: context.phase + 1})));
// and load the macro definition into the environment
macroDefinition = loadMacroDef(head.body, context, context.phase + 1);
var name = head.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, head.name[0]);
addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope);
context.env.names.set(name, true);
context.env.set(resolve(nameStx, context.phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: head.name
});
}
if (head.isLetMacro && expandCount < maxExpands) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({phase: context.phase + 1},
context)));
// and load the macro definition into the environment
macroDefinition = loadMacroDef(head.body, context, context.phase + 1);
var freshName = fresh();
var name = head.name.map(unwrapSyntax).join("");
var oldName = head.name;
var nameStx = syn.makeIdent(name, head.name[0]);
var renamedName = nameStx.rename(nameStx, freshName);
// store a reference to the full name in the props object.
// this allows us to communicate the original full name to
// `visit` later on.
renamedName.props.fullName = oldName;
head.name = [renamedName];
rest = _.map(rest, function(stx) {
return stx.rename(nameStx, freshName);
});
context.env.names.set(name, true);
context.env.set(resolve(renamedName, context.phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: oldName
});
}
if (head.isOperatorDefinition) {
// raw function primitive form
if(!(head.body[0] && head.body[0].token.type === parser.Token.Keyword &&
head.body[0].token.value === "function")) {
throwSyntaxError("load macro",
"Primitive macro form must contain a function for the macro body",
head.body);
}
// expand the body
head.body = expand(head.body,
makeExpanderContext(_.extend({phase: context.phase + 1},
context)));
// and load the macro definition into the environment
var opDefinition = loadMacroDef(head.body, context, context.phase + 1);
var name = head.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, head.name[0]);
addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope);
var resolvedName = resolve(nameStx, context.phase);
var opObj = context.env.get(resolvedName);
if (!opObj) {
opObj = {
isOp: true,
builtin: builtinMode,
fullName: head.name
}
}
assert(unwrapSyntax(head.type) === "binary" ||
unwrapSyntax(head.type) === "unary",
"operator must either be binary or unary");
opObj[unwrapSyntax(head.type)] = {
fn: opDefinition,
prec: head.prec.token.value,
assoc: head.assoc ? head.assoc.token.value : null
};
context.env.names.set(name, true);
context.env.set(resolvedName, opObj);
}
if (head.isNamedFun) {
addToDefinitionCtx([head.name], context.defscope, true, context.paramscope);
}
if (head.isVariableStatement ||
head.isLetStatement ||
head.isConstStatement) {
addToDefinitionCtx(_.map(head.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
if(head.isBlock && head.body.isDelimiter) {
head.body.delim.token.inner.forEach(function(term) {
if (term.isVariableStatement) {
addToDefinitionCtx(_.map(term.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
});
}
if(head.isDelimiter) {
head.delim.token.inner.forEach(function(term) {
if (term.isVariableStatement) {
addToDefinitionCtx(_.map(term.decls, function(decl) { return decl.ident; }),
context.defscope,
true,
context.paramscope);
}
});
}
if (head.isForStatement) {
var forCond = head.cond.token.inner;
if(forCond[0] && resolve(forCond[0], context.phase) === "let" &&
forCond[1] && forCond[1].token.type === parser.Token.Identifier) {
var letNew = fresh();
var letId = forCond[1];
forCond = forCond.map(function(stx) {
return stx.rename(letId, letNew);
});
// hack: we want to do the let renaming here, not
// in the expansion of `for (...)` so just remove the `let`
// keyword
head.cond.token.inner = expand([forCond[0]], context)
.concat(expand(forCond.slice(1), context));
// nice and easy case: `for (...) { ... }`
if (rest[0] && rest[0].token.value === "{}") {
rest[0] = rest[0].rename(letId, letNew);
} else {
// need to deal with things like `for (...) if (...) log(...)`
var bodyEnf = enforest(rest, context);
var bodyDestructed = bodyEnf.result.destruct(context);
var renamedBodyTerm = bodyEnf.result.rename(letId, letNew);
tagWithTerm(renamedBodyTerm, bodyDestructed);
rest = bodyEnf.rest;
prevStx = bodyDestructed.reverse().concat(prevStx);
prevTerms = [renamedBodyTerm].concat(prevTerms);
}
} else {
head.cond.token.inner = expand(head.cond.token.inner, context);
}
}
}
return {
// prevTerms are stored in reverse for the purposes of infix
// lookbehind matching, so we need to re-reverse them.
terms: prevTerms ? prevTerms.reverse() : [],
restStx: restStx,
context: context,
};
}
function addToDefinitionCtx(idents, defscope, skipRep, paramscope) {
assert(idents && idents.length > 0, "expecting some variable identifiers");
// flag for skipping repeats since we reuse this function to place both
// variables declarations (which need to skip redeclarations) and
// macro definitions which don't
skipRep = skipRep || false;
_.chain(idents)
.filter(function(id) {
if (skipRep) {
/*
When var declarations repeat in the same function scope:
var x = 24;
...
var x = 42;
we just need to use the first renaming and leave the
definition context as is.
*/
var varDeclRep = _.find(defscope, function(def) {
return def.id.token.value === id.token.value &&
arraysEqual(marksof(def.id.context), marksof(id.context));
});
/*
When var declaration repeat one of the function parameters:
function foo(x) {
var x;
}
we don't need to add the var to the definition context.
*/
var paramDeclRep = _.find(paramscope, function(param) {
return param.token.value === id.token.value &&
arraysEqual(marksof(param.context), marksof(id.context));
});
return (typeof varDeclRep === 'undefined') &&
(typeof paramDeclRep === 'undefined');
}
return true;
}).each(function(id) {
var name = fresh();
defscope.push({
id: id,
name: name
});
});
}
// similar to `parse2` in the honu paper except here we
// don't generate an AST yet
// @ (TermTreeObject, ExpanderContext) -> TermTreeObject
function expandTermTreeToFinal (term, context) {
assert(context && context.env, "environment map is required");
if (term.isArrayLiteral) {
term.array.delim.token.inner = expand(term.array.delim.token.inner, context);
return term;
} else if (term.isBlock) {
term.body.delim.token.inner = expand(term.body.delim.token.inner, context);
return term;
} else if (term.isParenExpression) {
term.args = _.map(term.args, function(arg) {
return expandTermTreeToFinal(arg, context);
});
return term;
} else if (term.isCall) {
term.fun = expandTermTreeToFinal(term.fun, context);
term.args = expandTermTreeToFinal(term.args, context);
return term;
} else if (term.isReturnStatement) {
term.expr = expandTermTreeToFinal(term.expr, context);
return term;
} else if (term.isUnaryOp) {
term.expr = expandTermTreeToFinal(term.expr, context);
return term;
} else if (term.isBinOp || term.isAssignmentExpression) {
term.left = expandTermTreeToFinal(term.left, context);
term.right = expandTermTreeToFinal(term.right, context);
return term;
} else if (term.isObjGet) {
term.left = expandTermTreeToFinal(term.left, context);
term.right.delim.token.inner = expand(term.right.delim.token.inner, context);
return term;
} else if (term.isObjDotGet) {
term.left = expandTermTreeToFinal(term.left, context);
term.right = expandTermTreeToFinal(term.right, context);
return term;
} else if (term.isConditionalExpression) {
term.cond = expandTermTreeToFinal(term.cond, context);
term.tru = expandTermTreeToFinal(term.tru, context);
term.fls = expandTermTreeToFinal(term.fls, context);
return term;
} else if (term.isVariableDeclaration) {
if (term.init) {
term.init = expandTermTreeToFinal(term.init, context);
}
return term;
} else if (term.isVariableStatement) {
term.decls = _.map(term.decls, function(decl) {
return expandTermTreeToFinal(decl, context);
});
return term;
} else if (term.isDelimiter) {
// expand inside the delimiter and then continue on
term.delim.token.inner = expand(term.delim.token.inner, context);
return term;
} else if (term.isNamedFun ||
term.isAnonFun ||
term.isCatchClause ||
term.isArrowFun ||
term.isModule) {
// function definitions need a bunch of hygiene logic
// push down a fresh definition context
var newDef = [];
var paramSingleIdent = term.params && term.params.token.type === parser.Token.Identifier;
var params;
if (term.params && term.params.token.type === parser.Token.Delimiter) {
params = term.params;
} else if (paramSingleIdent) {
params = term.params;
} else {
params = syn.makeDelim("()", [], null);
}
var bodies;
if (Array.isArray(term.body)) {
bodies = syn.makeDelim("{}", term.body, null);
} else {
bodies = term.body;
}
bodies = bodies.addDefCtx(newDef);
var paramNames = _.map(getParamIdentifiers(params), function(param) {
var freshName = fresh();
return {
freshName: freshName,
originalParam: param,
renamedParam: param.rename(param, freshName)
};
});
var bodyContext = makeExpanderContext(_.defaults({
defscope: newDef,
// paramscope is used to filter out var redeclarations
paramscope: paramNames.map(function(p) {
return p.renamedParam;
})
}, context));
// rename the function body for each of the parameters
var renamedBody = _.reduce(paramNames, function(accBody, p) {
return accBody.rename(p.originalParam, p.freshName)
}, bodies);
renamedBody = renamedBody;
var expandedResult = expandToTermTree(renamedBody.token.inner, bodyContext);
var bodyTerms = expandedResult.terms;
if(expandedResult.restStx) {
// The expansion was halted prematurely. Just stop and
// return what we have so far, along with the rest of the syntax
renamedBody.token.inner = expandedResult.terms.concat(expandedResult.restStx);
if(Array.isArray(term.body)) {
term.body = renamedBody.token.inner;
}
else {
term.body = renamedBody;
}
return term;
}
var renamedParams = _.map(paramNames, function(p) { return p.renamedParam});
var flatArgs;
if (paramSingleIdent) {
flatArgs = renamedParams[0];
} else {
var puncCtx = (term.params || null);
flatArgs = syn.makeDelim("()",
joinSyntax(renamedParams, syn.makePunc(",", puncCtx)),
puncCtx);
}
var expandedArgs = expand([flatArgs], bodyContext);
assert(expandedArgs.length === 1, "should only get back one result");
// stitch up the function with all the renamings
if (term.params) {
term.params = expandedArgs[0];
}
bodyTerms = _.map(bodyTerms, function(bodyTerm) {
// add the definition context to the result of
// expansion (this makes sure that syntax objects
// introduced by expansion have the def context)
if (bodyTerm.isBlock) {
// we need to expand blocks before adding the defctx since
// blocks defer macro expansion.
var blockFinal = expandTermTreeToFinal(bodyTerm,
expandedResult.context);
return blockFinal.addDefCtx(newDef);
} else {
var termWithCtx = bodyTerm.addDefCtx(newDef);
// finish expansion
return expandTermTreeToFinal(termWithCtx,
expandedResult.context);
}
})
if (term.isModule) {
bodyTerms.forEach(bodyTerm -> {
if (bodyTerm.isExport) {
if (bodyTerm.name.token.type == parser.Token.Delimiter &&
bodyTerm.name.token.value === "{}") {
bodyTerm.name.token.inner
|> filterCommaSep
|> names -> names.forEach(name -> {
term.exports.push(name);
});
} else {
throwSyntaxError("expand", "not valid export type", bodyTerm.name);
}
}
});
}
renamedBody.token.inner = bodyTerms;
if (Array.isArray(term.body)) {
term.body = renamedBody.token.inner;
} else {
term.body = renamedBody;
}
// and continue expand the rest
return term;
}
// the term is fine as is
return term;
}
// @ let TermTree = {}
// similar to `parse` in the honu paper
// @ ([...SyntaxObject], ExpanderContext) -> [...TermTreeObject]
function expand(stx, context) {
assert(context, "must provide an expander context");
var trees = expandToTermTree(stx, context);
var terms = _.map(trees.terms, function(term) {
return expandTermTreeToFinal(term, trees.context);
});
if(trees.restStx) {
terms.push.apply(terms, trees.restStx);
}
return terms;
}
function makeExpanderContext(o) {
o = o || {};
var env = o.env || new StringMap();
if (!env.names) {
env.names = new StringMap();
}
return Object.create(Object.prototype, {
filename: {value: o.filename,
writable: false, enumerable: true, configurable: false},
requireModule: {value: o.requireModule,
writable: false, enumerable: true, configurable: false},
env: {value: env,
writable: false, enumerable: true, configurable: false},
defscope: {value: o.defscope,
writable: false, enumerable: true, configurable: false},
paramscope: {value: o.paramscope,
writable: false, enumerable: true, configurable: false},
templateMap: {value: o.templateMap || new StringMap(),
writable: false, enumerable: true, configurable: false},
patternMap: {value: o.patternMap || new StringMap(),
writable: false, enumerable: true, configurable: false},
mark: {value: o.mark,
writable: false, enumerable: true, configurable: false},
phase: {value: o.phase,
writable: false, enumerable: true, configurable: false},
implicitImport: {value: o.implicitImport || new StringMap(),
writable: false, enumerable: true, configurable: false}
});
}
function makeModuleExpanderContext(options, templateMap, patternMap, phase) {
var requireModule = options ? options.requireModule : undefined;
var filename = options && options.filename ? options.filename : "<anonymous module>";
return makeExpanderContext({
filename: filename,
requireModule: requireModule,
templateMap: templateMap,
patternMap: patternMap,
phase: phase
});
}
function makeTopLevelExpanderContext(options) {
var requireModule = options ? options.requireModule : undefined;
var filename = options && options.filename ? options.filename : "<anonymous module>";
return makeExpanderContext({
filename: filename,
requireModule: requireModule
});
}
// a hack to make the top level hygiene work out
function expandTopLevel(stx, moduleContexts, options) {
moduleContexts = moduleContexts || [];
options = options || {};
options.flatten = options.flatten != null ? options.flatten : true;
maxExpands = options.maxExpands || Infinity;
expandCount = 0;
var context = makeTopLevelExpanderContext(options);
var modBody = syn.makeDelim("{}", stx, null);
modBody = _.reduce(moduleContexts, function(acc, mod) {
context.env.extend(mod.env);
context.env.names.extend(mod.env.names);
return loadModuleExports(acc, context.env, mod.exports, mod.env);
}, modBody);
var res = expand([syn.makeIdent("module", null), modBody], context);
res = res[0].destruct(context, {stripCompileTerm: true});
res = res[0].token.inner;
return options.flatten ? flatten(res) : res;
}
// @ (ModuleTerm, ExpanderContext) -> ModuleTerm
function collectImports(mod, context) {
// TODO: this is currently just grabbing the imports from the
// very beginning of the file. It really should be able to mix
// imports/exports/statements at the top level.
var imports = [];
var res;
var rest = mod.body;
// #lang "sweet" expands to imports for the basic macros for sweet.js
// eventually this should hook into module level extensions
if (unwrapSyntax(mod.lang) !== "base" &&
unwrapSyntax(mod.lang) !== "js") {
var defaultImports = [
"quoteSyntax",
"syntax",
"#",
"syntaxCase",
"macro",
"withSyntax",
"letstx",
"macroclass",
"operator"
];
defaultImports = defaultImports.map(name -> syn.makeIdent(name, null));
imports.push(ImportForMacros.create(syn.makeDelim("{}", joinSyntax(defaultImports,
syn.makePunc(",", null)),
null),
mod.lang));
imports.push(Import.create(syn.makeKeyword("import", null),
syn.makeDelim("{}", joinSyntax(defaultImports,
syn.makePunc(",", null)),
null),
syn.makeIdent("from", null),
mod.lang));
}
while (true) {
res = enforest(rest, context);
if (res.result && (res.result.isImport || res.result.isImportForMacros)) {
imports.push(res.result);
rest = res.rest;
} else {
break;
}
}
return Module.create(mod.name,
mod.lang,
rest,
imports,
mod.exports);
}
// @ let SweetOptions = {
// flatten: ?Bool
// }
// @ (Str, ModuleTerm) -> Str
function resolvePath(name, parent) {
var path = require("path");
var resolveSync = require("resolve/lib/sync");
var root = path.dirname(unwrapSyntax(parent.name));
var fs = require("fs");
if (name[0] === ".") {
name = path.resolve(root, name);
}
return resolveSync(name, {
basedir: root,
extensions: ['.js', '.sjs']
});
}
// @ (Str, [...SyntaxObject]) -> ModuleTerm
function createModule(name, body) {
if (body && body[0] && body[1] && body[2] &&
unwrapSyntax(body[0]) === "#" &&
unwrapSyntax(body[1]) === "lang" &&
body[2].token.type === parser.Token.StringLiteral) {
// consume optional semicolon
var rest = body[3] && body[3].token.value === ";" &&
body[3].token.type == parser.Token.Punctuator ? body.slice(4) : body.slice(3);
return Module.create(syn.makeValue(name, null),
body[2],
rest,
[],
[]);
}
return Module.create(syn.makeValue(name, null),
syn.makeValue("base", null),
body,
[],
[]);
}
// @ (Str) -> ModuleTerm
function loadModule(name) {
// node specific code
var fs = require("fs");
return fs.readFileSync(name, 'utf8')
|> parser.read |> body -> {
return createModule(name, body)
};
}
// @ (ModuleTerm, Num, ExpanderContext, SweetOptions) -> ExpanderContext
function invoke(mod, phase, context, options) {
if (unwrapSyntax(mod.lang) === "base") {
var exported = require(unwrapSyntax(mod.name));
Object.keys(exported).forEach(exp -> {
var freshName = fresh();
var expName = syn.makeIdent(exp, null);
var renamed = expName.rename(expName, freshName)
mod.exports.push(renamed);
context.env.set(resolve(renamed, phase), {
value: exported[exp]
});
context.env.names.set(exp, true);
})
} else {
mod.imports.forEach(imp -> {
var modToImport = loadImport(imp, mod, options, context);
if (imp.isImport) {
context = invoke(modToImport, phase, context, options);
}
});
var code = mod.body
|> terms -> terms.map(term -> term.destruct(context, {stripCompileTerm: true,
stripModuleTerm: true}))
|> _.flatten
|> flatten
|> parser.parse
|> codegen.generate
var global = {
console: console
};
vm.runInNewContext(code, global);
mod.exports.forEach(exp -> {
var expName = resolve(exp, phase);
var expVal = global[expName];
context.env.set(expName, {value: expVal});
context.env.names.set(unwrapSyntax(exp), true);
});
}
return context;
}
// @ (ModuleTerm, Num, ExpanderContext, SweetOptions) -> ExpanderContext
function visit(mod, phase, context, options) {
var defctx = [];
// we don't need to visit base modules
if (unwrapSyntax(mod.lang) === "base") {
return context;
}
mod.body = mod.body.map(term -> term.addDefCtx(defctx));
// reset the exports
mod.exports = [];
mod.imports.forEach(imp -> {
var modToImport = loadImport(imp, mod, options, context);
if(imp.isImport) {
context = visit(modToImport, phase, context, options);
} else if (imp.isImportForMacros) {
context = invoke(modToImport, phase + 1, context, options);
context = visit(modToImport, phase + 1, context, options);
} else {
assert(false, "not implemented yet");
}
bindImportInMod(imp, mod, modToImport, context, phase);
});
mod.body.forEach(term -> {
var name;
var macroDefinition;
if (term.isMacro) {
macroDefinition = loadMacroDef(term.body, context, phase + 1);
name = unwrapSyntax(term.name[0]);
context.env.names.set(name, true);
context.env.set(resolve(term.name[0], phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: term.name
});
}
if (term.isLetMacro) {
macroDefinition = loadMacroDef(term.body, context, phase + 1);
// compilation collapses multi-token let macro names into single identifier
name = unwrapSyntax(term.name[0]);
context.env.names.set(name, true);
context.env.set(resolve(term.name[0], phase), {
fn: macroDefinition,
isOp: false,
builtin: builtinMode,
fullName: term.name[0].props.fullName
});
}
if (term.isOperatorDefinition) {
var opDefinition = loadMacroDef(term.body, context, phase + 1);
name = term.name.map(unwrapSyntax).join("");
var nameStx = syn.makeIdent(name, term.name[0]);
addToDefinitionCtx([nameStx], defctx, false, []);
var resolvedName = resolve(nameStx, phase);
var opObj = context.env.get(resolvedName);
if (!opObj) {
opObj = {
isOp: true,
builtin: builtinMode,
fullName: term.name
}
}
assert(unwrapSyntax(term.type) === "binary" ||
unwrapSyntax(term.type) === "unary",
"operator must either be binary or unary");
opObj[unwrapSyntax(term.type)] = {
fn: opDefinition,
prec: term.prec.token.value,
assoc: term.assoc ? term.assoc.token.value : null
};
context.env.names.set(name, true);
context.env.set(resolvedName, opObj);
}
if (term.isExport) {
if (term.name.token.type === parser.Token.Delimiter &&
term.name.token.value === "{}") {
term.name.token.inner
|> filterCommaSep
|> names -> names.forEach(name -> {
mod.exports.push(name);
});
} else {
throwSyntaxError("visit", "not valid export", term.name);
}
}
});
return context;
}
// a version of map where the callback only runs on the non comma items in
// the comma separated list.
function mapCommaSep(l, f) {
return l.map((stx, idx)-> {
if (idx % 2 !== 0 && (stx.token.type !== parser.Token.Punctuator ||
stx.token.value !== ",")) {
throwSyntaxError("import",
"expecting a comma separated list",
stx);
} else if (idx % 2 !== 0) {
return stx;
} else {
return f(stx);
}
});
}
function filterCommaSep(stx) {
return stx.filter((stx, idx) -> {
if (idx % 2 !== 0 && (stx.token.type !== parser.Token.Punctuator ||
stx.token.value !== ",")) {
throwSyntaxError("import",
"expecting a comma separated list",
stx);
} else if (idx % 2 !== 0) {
return false;
} else {
return true;
}
});
}
// @ (ImportTerm, ModuleTerm, SweetOptions, ExpanderContext) -> ModuleTerm
function loadImport(imp, parent, options, context) {
var modToImport;
var modFullPath = resolvePath(unwrapSyntax(imp.from), parent);
if(!availableModules.has(modFullPath)) {
// load it
modToImport = loadModule(modFullPath)
|> loaded -> expandModule(loaded,
options,
context.templateMap,
context.patternMap).mod;
availableModules.set(modFullPath, modToImport);
} else {
modToImport = availableModules.get(modFullPath);
}
return modToImport;
}
// @ (ImportTerm, ModuleTerm, ModuleTerm, ExpanderContext, Num) -> Void
// mutating mod
function bindImportInMod(imp, mod, modToImport, context, phase) {
if (imp.names.token.type === parser.Token.Delimiter) {
if (imp.names.token.inner.length === 0) {
throwSyntaxCaseError("compileModule",
"must include names to import",
imp.names);
} else {
// first collect the import names and their associated bindings
var renamedNames = imp.names.token.inner
|> filterCommaSep
|> names -> names.map(importName -> {
var isBase = unwrapSyntax(modToImport.lang) === "base";
var inExports = _.find(modToImport.exports, expTerm -> {
if (importName.token.type === parser.Token.Delimiter) {
return expTerm.token.type === parser.Token.Delimiter &&
syntaxInnerValuesEq(importName, expTerm);
}
return expTerm.token.value === importName.token.value
});
if ((!inExports) && (!isBase)) {
throwSyntaxError("compile",
"the imported name `" +
unwrapSyntax(importName) +
"` was not exported from the module",
importName);
}
var exportName, trans, exportNameStr;
if (!inExports) {
// case when importing from a non ES6
// module but not for macros so the module
// was not invoked and thus nothing in the
// context for this name
if (importName.token.type === parser.Token.Delimiter) {
exportNameStr = importName.map(unwrapSyntax).join('');
} else {
exportNameStr = unwrapSyntax(importName);
}
trans = null;
} else if (inExports.token.type === parser.Token.Delimiter) {
exportName = inExports.token.inner;
exportNameStr = exportName.map(unwrapSyntax).join('');
trans = getValueInEnv(exportName[0],
exportName.slice(1),
context,
phase);
} else {
exportName = inExports;
exportNameStr = unwrapSyntax(exportName);
trans = getValueInEnv(exportName,
[],
context,
phase);
}
var newParam = syn.makeIdent(exportNameStr, importName);
var newName = fresh();
return {
original: newParam,
renamed: newParam.imported(newParam, newName, phase),
name: newName,
trans: trans
};
});
// set the new bindings in the context
renamedNames.forEach(name -> {
context.env.names.set(unwrapSyntax(name.renamed), true);
context.env.set(resolve(name.renamed, phase),
name.trans);
// setup a reverse map from each import name to
// the import term but only for runtime values
if (name.trans === null || (name.trans && name.trans.value)) {
var resolvedName = resolve(name.renamed, phase);
var origName = resolve(name.original, phase);
context.implicitImport.set(resolvedName, imp);
}
mod.body = mod.body.map(stx -> stx.imported(name.original,
name.name,
phase));
});
imp.names = syn.makeDelim("{}",
joinSyntax(renamedNames.map(name -> name.renamed),
syn.makePunc(",", imp.names)),
imp.names);
}
} else {
assert(false, "not implemented yet");
}
}
function expandModule(mod, options, templateMap, patternMap) {
var context = makeModuleExpanderContext(options, templateMap, patternMap, 0);
return {
context: context,
mod: collectImports(mod, context) |> mod -> {
mod.imports.forEach(imp -> {
var modToImport = loadImport(imp, mod, options, context);
if (imp.isImport) {
context = visit(modToImport, 0, context, options);
} else if (imp.isImportForMacros) {
context = invoke(modToImport, 1, context, options);
context = visit(modToImport, 1, context, options);
} else {
assert(false, "not implemented yet");
}
var importPhase = imp.isImport ? 0 : 1;
bindImportInMod(imp, mod, modToImport, context, importPhase);
});
return expandTermTreeToFinal(mod, context);
}
};
}
function filterCompileNames(stx, context) {
assert(stx.token.type === parser.Token.Delimiter, "must be a delimter");
var runtimeNames = stx.token.inner
|> filterCommaSep
|> names -> {
return names.filter(name -> {
if (name.token.type === parser.Token.Delimiter) {
return !nameInEnv(name.token.inner[0],
name.token.inner.slice(1),
context,
0);
} else {
return !nameInEnv(name, [], context, 0);
}
});
};
var newInner = runtimeNames.reduce((acc, name, idx, orig) -> {
acc.push(name);
if (orig.length - 1 !== idx) { // don't add trailing comma
acc.push(syn.makePunc(",", name));
}
return acc;
}, []);
return syn.makeDelim("{}", newInner, stx);
}
// Takes an expanded module term and flattens it.
// @ (ModuleTerm, SweetOptions, TemplateMap, PatternMap) -> [...SyntaxObject]
function flattenModule(mod, context) {
// filter the imports to just the imports and names that are
// actually available at runtime
var imports = mod.imports.reduce((acc, imp) -> {
if (imp.isImportForMacros) {
return acc;
}
if (imp.names.token.type === parser.Token.Delimiter) {
imp.names = filterCompileNames(imp.names, context);
if (imp.names.token.inner.length === 0) {
return acc;
}
return acc.concat(imp);
} else {
assert(false, "not implemented yet");
}
}, []);
// filter the exports to just the exports and names that are
// actually available at runtime
var output = mod.body.reduce((acc, term) -> {
if (term.isExport) {
if (term.name.token.type === parser.Token.Delimiter) {
term.name = filterCompileNames(term.name, context);
if (term.name.token.inner.length === 0) {
return acc;
}
} else {
assert(false, "not implemented yet");
}
}
return acc.concat(term.destruct(context, {stripCompileTerm: true}));
}, []);
output = output
|> flatten
|> output -> output.map(stx -> {
var name = resolve(stx, 0);
// collect the implicit imports (those imports that
// must be included because a macro expanded to a reference
// to an import from some other module)
if (context.implicitImport.has(name)) {
imports.push(context.implicitImport.get(name));
}
return stx
});
// flatten everything
var flatImports = imports.reduce((acc, imp) -> {
return acc.concat(flatten(imp.destruct(context).concat(syn.makePunc(";", imp.names))));
}, []);
return {
imports: imports,
body: flatImports.concat(output)
};
}
function flattenImports(imports, mod, context) {
return imports.reduce((acc, imp) -> {
var modFullPath = resolvePath(unwrapSyntax(imp.from), mod);
if (availableModules.has(modFullPath)) {
var flattened = flattenModule(availableModules.get(modFullPath), context);
acc.push({
path: modFullPath,
code: flattened.body
});
acc = acc.concat(flattenImports(flattened.imports, mod, context))
return acc;
} else {
assert(false, "module was unexpectedly not available for compilation" + modFullPath);
}
}, []);
}
// The entry point to expanding with modules. Starting from the
// token tree of a module, compile it and all its imports. Return
// an array of all the compiled modules.
// @ ([...SyntaxObject], {filename: Str}) -> [...{ path: Str, code: [...SyntaxObject]}]
function compileModule(stx, options) {
var fs = require("fs");
var filename = options && typeof options.filename !== 'undefined'
? fs.realpathSync(options.filename)
: "(anonymous module)";
maxExpands = Infinity;
expandCount = 0;
var mod = createModule(filename, stx);
// the template and pattern maps are global for every module
var templateMap = new StringMap();
var patternMap = new StringMap();
availableModules = new StringMap();
var expanded = expandModule(mod, options, templateMap, patternMap);
var flattened = flattenModule(expanded.mod, expanded.context);
var compiledModules = flattenImports(flattened.imports, expanded.mod, expanded.context);
return [{
path: filename,
code: flattened.body
}].concat(compiledModules);
}
function loadModuleExports(stx, newEnv, exports, oldEnv) {
return _.reduce(exports, function(acc, param) {
var newName = fresh();
var transformer = oldEnv.get(resolve(param.oldExport));
if (transformer) {
newEnv.set(resolve(param.newParam.rename(param.newParam, newName)),
transformer);
return acc.rename(param.newParam, newName);
} else {
return acc;
}
}, stx);
}
// break delimiter tree structure down to flat array of syntax objects
// @ ([...SyntaxObject]) -> [...SyntaxObject]
function flatten(stx) {
return _.reduce(stx, function(acc, stx) {
if (stx.token.type === parser.Token.Delimiter) {
var openParen = syntaxFromToken({
type: parser.Token.Punctuator,
value: stx.token.value[0],
range: stx.token.startRange,
sm_range: (typeof stx.token.sm_startRange == 'undefined'
? stx.token.startRange
: stx.token.sm_startRange),
lineNumber: stx.token.startLineNumber,
sm_lineNumber: (typeof stx.token.sm_startLineNumber == 'undefined'
? stx.token.startLineNumber
: stx.token.sm_startLineNumber),
lineStart: stx.token.startLineStart,
sm_lineStart: (typeof stx.token.sm_startLineStart == 'undefined'
? stx.token.startLineStart
: stx.token.sm_startLineStart)
}, stx);
var closeParen = syntaxFromToken({
type: parser.Token.Punctuator,
value: stx.token.value[1],
range: stx.token.endRange,
sm_range: (typeof stx.token.sm_endRange == 'undefined'
? stx.token.endRange
: stx.token.sm_endRange),
lineNumber: stx.token.endLineNumber,
sm_lineNumber: (typeof stx.token.sm_endLineNumber == 'undefined'
? stx.token.endLineNumber
: stx.token.sm_endLineNumber),
lineStart: stx.token.endLineStart,
sm_lineStart: (typeof stx.token.sm_endLineStart == 'undefined'
? stx.token.endLineStart
: stx.token.sm_endLineStart)
}, stx);
if (stx.token.leadingComments) {
openParen.token.leadingComments = stx.token.leadingComments;
}
if (stx.token.trailingComments) {
openParen.token.trailingComments = stx.token.trailingComments;
}
acc.push(openParen);
push.apply(acc, flatten(stx.token.inner));
acc.push(closeParen);
return acc;
}
stx.token.sm_lineNumber = typeof stx.token.sm_lineNumber != 'undefined'
? stx.token.sm_lineNumber
: stx.token.lineNumber;
stx.token.sm_lineStart = typeof stx.token.sm_lineStart != 'undefined'
? stx.token.sm_lineStart
: stx.token.lineStart;
stx.token.sm_range = typeof stx.token.sm_range != 'undefined'
? stx.token.sm_range
: stx.token.range;
acc.push(stx);
return acc;
}, []);
}
exports.StringMap = StringMap;
exports.enforest = enforest;
exports.expand = expandTopLevel;
exports.compileModule = compileModule;
exports.resolve = resolve;
exports.get_expression = get_expression;
exports.getName = getName;
exports.getValueInEnv = getValueInEnv;
exports.nameInEnv = nameInEnv;
exports.makeExpanderContext = makeExpanderContext;
exports.Expr = Expr;
exports.VariableStatement = VariableStatement;
exports.tokensToSyntax = syn.tokensToSyntax;
exports.syntaxToTokens = syn.syntaxToTokens;
}));
| moving module collection into expandTermTree
| src/expander.js | moving module collection into expandTermTree | <ide><path>rc/expander.js
<ide> // @ let ExpanderContext = {}
<ide> // {
<ide> // filename: Str,
<del> // requireModule: Str,
<ide> // env: {},
<ide> // defscope: {},
<ide> // paramscope: {},
<ide>
<ide> dataclass ModuleTerm () extends TermTree;
<ide>
<del> dataclass Module (name, lang, body, imports, exports)extends ModuleTerm;
<add> dataclass Module (body) extends ModuleTerm;
<ide> dataclass Import (kw, names, fromkw, from) extends ModuleTerm;
<ide> dataclass ImportForMacros (names, from) extends ModuleTerm;
<ide> dataclass Export (kw, name) extends ModuleTerm;
<ide> makePunc: syn.makePunc,
<ide> makeDelim: syn.makeDelim,
<ide> filename: context.filename,
<del> require: function(id) {
<del> if (context.requireModule) {
<del> return context.requireModule(id, context.filename);
<del> }
<del> return require(id);
<del> },
<ide> getExpr: function(stx) {
<ide> var r;
<ide> if (stx.length === 0) {
<ide> var destructed = tagWithTerm(head, f.result.destruct(context));
<ide> prevTerms = [head].concat(f.prevTerms);
<ide> prevStx = destructed.reverse().concat(f.prevStx);
<add>
<add> if (head.isImport) {
<add> // record the import in the module record for easier access
<add> context.moduleRecord.importEntries.push(head);
<add> // load up the (possibly cached) import module
<add> var importMod = loadImport(head, context);
<add> // visiting an imported module loads the compiletime values
<add> // into the compiletime environment for this phase
<add> context = visit(importMod.term, importMod.record, context.phase, context);
<add> // bind the imported names in the rest of the module
<add> // todo: how to handle references before an import?
<add> rest = bindImportInMod(head, rest, importMod.term, importMod.record, context, context.phase);
<add> }
<add>
<add> if (head.isImportForMacros) {
<add> // record the import in the module record for easier access
<add> context.moduleRecord.importEntries.push(head);
<add> // load up the (possibly cached) import module
<add> var importMod = loadImport(head, context);
<add> // invoking an imported module loads the runtime values
<add> // into the environment for this phase
<add> context = invoke(importMod.term, importMod.record, context.phase + 1, context);
<add> // visiting an imported module loads the compiletime values
<add> // into the compiletime environment for this phase
<add> context = visit(importMod.term, importMod.record, context.phase + 1, context);
<add> // bind the imported names in the rest of the module
<add> // todo: how to handle references before an import?
<add> rest = bindImportInMod(head, rest, importMod.term, importMod.record, context, context.phase + 1);
<add> }
<ide>
<ide> if (head.isMacro && expandCount < maxExpands) {
<ide> // raw function primitive form
<ide> bodyTerm.name.token.inner
<ide> |> filterCommaSep
<ide> |> names -> names.forEach(name -> {
<del> term.exports.push(name);
<add> context.moduleRecord.exportEntries.push(name);
<ide> });
<ide> } else {
<ide> throwSyntaxError("expand", "not valid export type", bodyTerm.name);
<ide> return Object.create(Object.prototype, {
<ide> filename: {value: o.filename,
<ide> writable: false, enumerable: true, configurable: false},
<del> requireModule: {value: o.requireModule,
<del> writable: false, enumerable: true, configurable: false},
<ide> env: {value: env,
<ide> writable: false, enumerable: true, configurable: false},
<ide> defscope: {value: o.defscope,
<ide> phase: {value: o.phase,
<ide> writable: false, enumerable: true, configurable: false},
<ide> implicitImport: {value: o.implicitImport || new StringMap(),
<del> writable: false, enumerable: true, configurable: false}
<add> writable: false, enumerable: true, configurable: false},
<add> moduleRecord: {value: o.moduleRecord || {},
<add> writable: false, enumerable: true, configurable: false}
<ide> });
<ide> }
<ide>
<del> function makeModuleExpanderContext(options, templateMap, patternMap, phase) {
<del> var requireModule = options ? options.requireModule : undefined;
<add> function makeModuleExpanderContext(filename, templateMap, patternMap, phase, moduleRecord) {
<add> return makeExpanderContext({
<add> filename: filename,
<add> templateMap: templateMap,
<add> patternMap: patternMap,
<add> phase: phase,
<add> moduleRecord: moduleRecord
<add> });
<add> }
<add>
<add> function makeTopLevelExpanderContext(options) {
<ide> var filename = options && options.filename ? options.filename : "<anonymous module>";
<ide> return makeExpanderContext({
<ide> filename: filename,
<del> requireModule: requireModule,
<del> templateMap: templateMap,
<del> patternMap: patternMap,
<del> phase: phase
<del> });
<del> }
<del>
<del> function makeTopLevelExpanderContext(options) {
<del> var requireModule = options ? options.requireModule : undefined;
<del> var filename = options && options.filename ? options.filename : "<anonymous module>";
<del> return makeExpanderContext({
<del> filename: filename,
<del> requireModule: requireModule
<ide> });
<ide> }
<ide>
<ide> }
<ide>
<ide>
<del> // @ (ModuleTerm, ExpanderContext) -> ModuleTerm
<del> function collectImports(mod, context) {
<del> // TODO: this is currently just grabbing the imports from the
<del> // very beginning of the file. It really should be able to mix
<del> // imports/exports/statements at the top level.
<del> var imports = [];
<del> var res;
<del> var rest = mod.body;
<del> // #lang "sweet" expands to imports for the basic macros for sweet.js
<del> // eventually this should hook into module level extensions
<del> if (unwrapSyntax(mod.lang) !== "base" &&
<del> unwrapSyntax(mod.lang) !== "js") {
<del> var defaultImports = [
<del> "quoteSyntax",
<del> "syntax",
<del> "#",
<del> "syntaxCase",
<del> "macro",
<del> "withSyntax",
<del> "letstx",
<del> "macroclass",
<del> "operator"
<del> ];
<del> defaultImports = defaultImports.map(name -> syn.makeIdent(name, null));
<del> imports.push(ImportForMacros.create(syn.makeDelim("{}", joinSyntax(defaultImports,
<del> syn.makePunc(",", null)),
<del> null),
<del> mod.lang));
<del> imports.push(Import.create(syn.makeKeyword("import", null),
<del> syn.makeDelim("{}", joinSyntax(defaultImports,
<del> syn.makePunc(",", null)),
<del> null),
<del> syn.makeIdent("from", null),
<del> mod.lang));
<del> }
<del> while (true) {
<del> res = enforest(rest, context);
<del> if (res.result && (res.result.isImport || res.result.isImportForMacros)) {
<del> imports.push(res.result);
<del> rest = res.rest;
<del> } else {
<del> break;
<del> }
<del> }
<del>
<del> return Module.create(mod.name,
<del> mod.lang,
<del> rest,
<del> imports,
<del> mod.exports);
<del> }
<del>
<del>
<del> // @ let SweetOptions = {
<del> // flatten: ?Bool
<del> // }
<del>
<del> // @ (Str, ModuleTerm) -> Str
<add> // @ (Str, Str) -> Str
<ide> function resolvePath(name, parent) {
<ide> var path = require("path");
<ide> var resolveSync = require("resolve/lib/sync");
<del> var root = path.dirname(unwrapSyntax(parent.name));
<add> var root = path.dirname(parent);
<ide> var fs = require("fs");
<ide> if (name[0] === ".") {
<ide> name = path.resolve(root, name);
<ide> });
<ide> }
<ide>
<del> // @ (Str, [...SyntaxObject]) -> ModuleTerm
<add> // (Str) -> [...SyntaxObject]
<add> function defaultImportStx(importPath, ctx) {
<add> var names = [
<add> "quoteSyntax",
<add> "syntax",
<add> "#",
<add> "syntaxCase",
<add> "macro",
<add> "withSyntax",
<add> "letstx",
<add> "macroclass",
<add> "operator"
<add> ];
<add>
<add> var importNames = names.map(name -> syn.makeIdent(name, ctx));
<add> var importForMacrosNames = names.map(name -> syn.makeIdent(name, ctx));
<add> // import { names ... } from "importPath" for macros
<add> var importForMacrosStmt = [syn.makeKeyword("import", ctx),
<add> syn.makeDelim("{}", joinSyntax(importForMacrosNames,
<add> syn.makePunc(",", ctx)),
<add> ctx),
<add> syn.makeIdent("from", ctx),
<add> syn.makeValue(importPath, ctx),
<add> syn.makeKeyword("for", ctx),
<add> syn.makeIdent("macros", ctx)];
<add>
<add> // import { names ... } from "importPath"
<add> var importStmt = [syn.makeKeyword("import", ctx),
<add> syn.makeDelim("{}", joinSyntax(importNames,
<add> syn.makePunc(",", ctx)),
<add> ctx),
<add> syn.makeIdent("from", ctx),
<add> syn.makeValue(importPath, ctx)];
<add>
<add> return importStmt.concat(importForMacrosStmt);
<add> }
<add>
<add> // @ (Str, [...SyntaxObject]) -> {
<add> // record: ModuleRecord,
<add> // term: ModuleTerm
<add> // }
<ide> function createModule(name, body) {
<add> var language = "base";
<add> var modBody = body;
<add>
<ide> if (body && body[0] && body[1] && body[2] &&
<ide> unwrapSyntax(body[0]) === "#" &&
<ide> unwrapSyntax(body[1]) === "lang" &&
<ide> body[2].token.type === parser.Token.StringLiteral) {
<add>
<add> language = unwrapSyntax(body[2]);
<ide> // consume optional semicolon
<del> var rest = body[3] && body[3].token.value === ";" &&
<add> modBody = body[3] && body[3].token.value === ";" &&
<ide> body[3].token.type == parser.Token.Punctuator ? body.slice(4) : body.slice(3);
<del> return Module.create(syn.makeValue(name, null),
<del> body[2],
<del> rest,
<del> [],
<del> []);
<del> }
<del> return Module.create(syn.makeValue(name, null),
<del> syn.makeValue("base", null),
<del> body,
<del> [],
<del> []);
<del> }
<del>
<del> // @ (Str) -> ModuleTerm
<add> }
<add>
<add> // insert the default import statements into the module body
<add> if (language !== "base" && language !== "js") {
<add> // "base" and "js" are currently special languages meaning don't
<add> // insert the default imports
<add> modBody = defaultImportStx(language, body[0]).concat(modBody);
<add> }
<add>
<add> return {
<add> record: {
<add> name: name,
<add> language: language,
<add> importEntries: [],
<add> exportEntries: []
<add> },
<add> term: Module.create(modBody)
<add> };
<add> }
<add>
<add> // @ (Str) -> {
<add> // record: ModuleRecord,
<add> // term: ModuleTerm
<add> // }
<ide> function loadModule(name) {
<ide> // node specific code
<ide> var fs = require("fs");
<ide>
<ide> }
<ide>
<del> // @ (ModuleTerm, Num, ExpanderContext, SweetOptions) -> ExpanderContext
<del> function invoke(mod, phase, context, options) {
<del> if (unwrapSyntax(mod.lang) === "base") {
<del> var exported = require(unwrapSyntax(mod.name));
<add> // For a given module, phase, and context load the runtime values
<add> // into the context and return the modified context
<add> // @ (ModuleTerm, ModuleRecord, Num, ExpanderContext) -> ExpanderContext
<add> function invoke(modTerm, modRecord, phase, context) {
<add> if (modRecord.language === "base") {
<add> // base modules can just use the normal require pipeline
<add> var exported = require(modRecord.name);
<ide> Object.keys(exported).forEach(exp -> {
<add> // create new bindings in the context
<ide> var freshName = fresh();
<ide> var expName = syn.makeIdent(exp, null);
<ide> var renamed = expName.rename(expName, freshName)
<ide>
<del> mod.exports.push(renamed);
<add> modRecord.exportEntries.push(renamed);
<ide> context.env.set(resolve(renamed, phase), {
<ide> value: exported[exp]
<ide> });
<ide> context.env.names.set(exp, true);
<ide> })
<ide> } else {
<del> mod.imports.forEach(imp -> {
<del> var modToImport = loadImport(imp, mod, options, context);
<add> // recursively invoke any imports in this module at this
<add> // phase and update the context
<add> modRecord.importEntries.forEach(imp -> {
<add> var importMod = loadImport(imp, context);
<ide> if (imp.isImport) {
<del> context = invoke(modToImport, phase, context, options);
<add> context = invoke(importMod.term, importMod.record, phase, context);
<ide> }
<ide> });
<ide>
<del> var code = mod.body
<add> // turn the module into text so we can eval it
<add> var code = modTerm.body
<ide> |> terms -> terms.map(term -> term.destruct(context, {stripCompileTerm: true,
<ide> stripModuleTerm: true}))
<ide> |> _.flatten
<ide> |> flatten
<ide> |> parser.parse
<ide> |> codegen.generate
<add>
<ide> var global = {
<ide> console: console
<ide> };
<ide>
<add> // eval but with a fresh heap
<ide> vm.runInNewContext(code, global);
<ide>
<del> mod.exports.forEach(exp -> {
<add> // update the exports with the runtime values
<add> modRecord.exportEntries.forEach(exp -> {
<ide> var expName = resolve(exp, phase);
<ide> var expVal = global[expName];
<ide> context.env.set(expName, {value: expVal});
<ide> }
<ide>
<ide>
<del> // @ (ModuleTerm, Num, ExpanderContext, SweetOptions) -> ExpanderContext
<del> function visit(mod, phase, context, options) {
<add> // For a given module, phase, and context, load the compiletime values into
<add> // the context and return the modified context
<add> // @ (ModuleTerm, ModuleRecord, Num, ExpanderContext) -> ExpanderContext
<add> function visit(modTerm, modRecord, phase, context) {
<ide> var defctx = [];
<del> // we don't need to visit base modules
<del> if (unwrapSyntax(mod.lang) === "base") {
<add> // don't need to visit base modules since they do not support macros
<add> if (modRecord.language === "base") {
<ide> return context;
<ide> }
<del> mod.body = mod.body.map(term -> term.addDefCtx(defctx));
<add> // add a visiting definition context since we are binding
<add> // macros in the module scope
<add> modTerm.body = modTerm.body.map(term -> term.addDefCtx(defctx));
<ide> // reset the exports
<del> mod.exports = [];
<del>
<del> mod.imports.forEach(imp -> {
<del> var modToImport = loadImport(imp, mod, options, context);
<add> modRecord.exportEntries = [];
<add>
<add> // for each of the imported modules, recursively visit and
<add> // invoke them at the appropriate phase and then bind the
<add> // imported names in this module
<add> modRecord.importEntries.forEach(imp -> {
<add> var importMod = loadImport(imp, context);
<ide>
<ide> if(imp.isImport) {
<del> context = visit(modToImport, phase, context, options);
<add> context = visit(importMod.term, importMod.record, phase, context);
<ide> } else if (imp.isImportForMacros) {
<del> context = invoke(modToImport, phase + 1, context, options);
<del> context = visit(modToImport, phase + 1, context, options);
<add> context = invoke(importMod.term, importMod.record, phase + 1, context);
<add> context = visit(importMod.term, importMod.record, phase + 1, context);
<ide> } else {
<add> // todo: arbitrary phase
<ide> assert(false, "not implemented yet");
<ide> }
<ide>
<del> bindImportInMod(imp, mod, modToImport, context, phase);
<add> modTerm.body = bindImportInMod(imp,
<add> modTerm.body,
<add> importMod.term,
<add> importMod.record,
<add> context,
<add> phase);
<ide> });
<ide>
<del> mod.body.forEach(term -> {
<add> // go through the module and load any compiletime values in to the context
<add> modTerm.body.forEach(term -> {
<ide> var name;
<ide> var macroDefinition;
<ide> if (term.isMacro) {
<ide> context.env.set(resolvedName, opObj);
<ide> }
<ide>
<add> // add the exported names to the module record
<ide> if (term.isExport) {
<ide> if (term.name.token.type === parser.Token.Delimiter &&
<ide> term.name.token.value === "{}") {
<ide> term.name.token.inner
<ide> |> filterCommaSep
<ide> |> names -> names.forEach(name -> {
<del> mod.exports.push(name);
<add> modRecord.exportEntries.push(name);
<ide> });
<ide> } else {
<ide> throwSyntaxError("visit", "not valid export", term.name);
<ide> }
<ide>
<ide>
<del> // @ (ImportTerm, ModuleTerm, SweetOptions, ExpanderContext) -> ModuleTerm
<del> function loadImport(imp, parent, options, context) {
<del> var modToImport;
<del> var modFullPath = resolvePath(unwrapSyntax(imp.from), parent);
<add> // @ (ImportTerm, ExpanderContext) -> {
<add> // term: ModuleTerm
<add> // record: ModuleRecord
<add> // }
<add> function loadImport(imp, context) {
<add> var modFullPath = resolvePath(unwrapSyntax(imp.from), context.filename);
<ide> if(!availableModules.has(modFullPath)) {
<ide> // load it
<del> modToImport = loadModule(modFullPath)
<del> |> loaded -> expandModule(loaded,
<del> options,
<del> context.templateMap,
<del> context.patternMap).mod;
<del> availableModules.set(modFullPath, modToImport);
<del> } else {
<del> modToImport = availableModules.get(modFullPath);
<del> }
<del> return modToImport;
<del> }
<del>
<del> // @ (ImportTerm, ModuleTerm, ModuleTerm, ExpanderContext, Num) -> Void
<del> // mutating mod
<del> function bindImportInMod(imp, mod, modToImport, context, phase) {
<del> if (imp.names.token.type === parser.Token.Delimiter) {
<del> if (imp.names.token.inner.length === 0) {
<del> throwSyntaxCaseError("compileModule",
<del> "must include names to import",
<del> imp.names);
<del> } else {
<del> // first collect the import names and their associated bindings
<del> var renamedNames = imp.names.token.inner
<del> |> filterCommaSep
<del> |> names -> names.map(importName -> {
<del> var isBase = unwrapSyntax(modToImport.lang) === "base";
<del>
<del> var inExports = _.find(modToImport.exports, expTerm -> {
<del> if (importName.token.type === parser.Token.Delimiter) {
<del> return expTerm.token.type === parser.Token.Delimiter &&
<del> syntaxInnerValuesEq(importName, expTerm);
<del> }
<del> return expTerm.token.value === importName.token.value
<del> });
<del> if ((!inExports) && (!isBase)) {
<del> throwSyntaxError("compile",
<del> "the imported name `" +
<del> unwrapSyntax(importName) +
<del> "` was not exported from the module",
<del> importName);
<del> }
<del>
<del> var exportName, trans, exportNameStr;
<del> if (!inExports) {
<del> // case when importing from a non ES6
<del> // module but not for macros so the module
<del> // was not invoked and thus nothing in the
<del> // context for this name
<del> if (importName.token.type === parser.Token.Delimiter) {
<del> exportNameStr = importName.map(unwrapSyntax).join('');
<del> } else {
<del> exportNameStr = unwrapSyntax(importName);
<del> }
<del> trans = null;
<del> } else if (inExports.token.type === parser.Token.Delimiter) {
<del> exportName = inExports.token.inner;
<del> exportNameStr = exportName.map(unwrapSyntax).join('');
<del> trans = getValueInEnv(exportName[0],
<del> exportName.slice(1),
<del> context,
<del> phase);
<del> } else {
<del> exportName = inExports;
<del> exportNameStr = unwrapSyntax(exportName);
<del> trans = getValueInEnv(exportName,
<del> [],
<del> context,
<del> phase);
<del> }
<del>
<del> var newParam = syn.makeIdent(exportNameStr, importName);
<del> var newName = fresh();
<del> return {
<del> original: newParam,
<del> renamed: newParam.imported(newParam, newName, phase),
<del> name: newName,
<del> trans: trans
<del> };
<del> });
<del>
<del> // set the new bindings in the context
<del> renamedNames.forEach(name -> {
<del> context.env.names.set(unwrapSyntax(name.renamed), true);
<del> context.env.set(resolve(name.renamed, phase),
<del> name.trans);
<del> // setup a reverse map from each import name to
<del> // the import term but only for runtime values
<del> if (name.trans === null || (name.trans && name.trans.value)) {
<del> var resolvedName = resolve(name.renamed, phase);
<del> var origName = resolve(name.original, phase);
<del> context.implicitImport.set(resolvedName, imp);
<del> }
<del>
<del> mod.body = mod.body.map(stx -> stx.imported(name.original,
<del> name.name,
<del> phase));
<del>
<add> var modToImport = loadModule(modFullPath)
<add> |> mod -> expandModule(mod.term,
<add> modFullPath,
<add> context.templateMap,
<add> context.patternMap,
<add> mod.record);
<add> var modPair = {
<add> term: modToImport.mod,
<add> record: modToImport.context.moduleRecord
<add> };
<add> availableModules.set(modFullPath, modPair);
<add> return modPair;
<add> }
<add> return availableModules.get(modFullPath);
<add> }
<add>
<add> // @ (ImportTerm, [...SyntaxObject], ModuleTerm, ModuleRecord, ExpanderContext, Num) -> Void
<add> function bindImportInMod(imp, stx, modTerm, modRecord, context, phase) {
<add> // todo: implement other import forms
<add> if (imp.names.token.type !== parser.Token.Delimiter) {
<add> assert(false, "not implemented yet");
<add> }
<add>
<add> if (imp.names.token.inner.length === 0) {
<add> throwSyntaxCaseError("compileModule",
<add> "must include names to import",
<add> imp.names);
<add> }
<add>
<add> // first collect the import names and their associated bindings
<add> var renamedNames = imp.names.token.inner
<add> |> filterCommaSep
<add> |> names -> names.map(importName -> {
<add> var isBase = modRecord.language === "base";
<add>
<add> var inExports = _.find(modRecord.exportEntries, expTerm -> {
<add> if (importName.token.type === parser.Token.Delimiter) {
<add> return expTerm.token.type === parser.Token.Delimiter &&
<add> syntaxInnerValuesEq(importName, expTerm);
<add> }
<add> return expTerm.token.value === importName.token.value
<ide> });
<del> imp.names = syn.makeDelim("{}",
<del> joinSyntax(renamedNames.map(name -> name.renamed),
<del> syn.makePunc(",", imp.names)),
<del> imp.names);
<del>
<del> }
<del> } else {
<del> assert(false, "not implemented yet");
<del> }
<del> }
<del>
<del> function expandModule(mod, options, templateMap, patternMap) {
<del> var context = makeModuleExpanderContext(options, templateMap, patternMap, 0);
<del>
<add> if (!(inExports || isBase)) {
<add> throwSyntaxError("compile",
<add> "the imported name `" +
<add> unwrapSyntax(importName) +
<add> "` was not exported from the module",
<add> importName);
<add> }
<add>
<add> var exportName, trans, exportNameStr;
<add> if (!inExports) {
<add> // case when importing from a non ES6
<add> // module but not for macros so the module
<add> // was not invoked and thus nothing in the
<add> // context for this name
<add> if (importName.token.type === parser.Token.Delimiter) {
<add> exportNameStr = importName.map(unwrapSyntax).join('');
<add> } else {
<add> exportNameStr = unwrapSyntax(importName);
<add> }
<add> trans = null;
<add> } else if (inExports.token.type === parser.Token.Delimiter) {
<add> exportName = inExports.token.inner;
<add> exportNameStr = exportName.map(unwrapSyntax).join('');
<add> trans = getValueInEnv(exportName[0],
<add> exportName.slice(1),
<add> context,
<add> phase);
<add> } else {
<add> exportName = inExports;
<add> exportNameStr = unwrapSyntax(exportName);
<add> trans = getValueInEnv(exportName,
<add> [],
<add> context,
<add> phase);
<add> }
<add>
<add> var newParam = syn.makeIdent(exportNameStr, importName);
<add> var newName = fresh();
<add> return {
<add> original: newParam,
<add> renamed: newParam.imported(newParam, newName, phase),
<add> name: newName,
<add> trans: trans
<add> };
<add> });
<add>
<add> // set the new bindings in the context
<add> renamedNames.forEach(name -> {
<add> context.env.names.set(unwrapSyntax(name.renamed), true);
<add> context.env.set(resolve(name.renamed, phase),
<add> name.trans);
<add> // setup a reverse map from each import name to
<add> // the import term but only for runtime values
<add> if (name.trans === null || (name.trans && name.trans.value)) {
<add> var resolvedName = resolve(name.renamed, phase);
<add> var origName = resolve(name.original, phase);
<add> context.implicitImport.set(resolvedName, imp);
<add> }
<add>
<add> });
<add> imp.names = syn.makeDelim("{}",
<add> joinSyntax(renamedNames.map(name -> name.renamed),
<add> syn.makePunc(",", imp.names)),
<add> imp.names);
<add>
<add> return stx.map(stx -> renamedNames.reduce((acc, name) -> {
<add> return acc.imported(name.original, name.name, phase);
<add> }, stx));
<add> }
<add>
<add> // (ModuleTerm, Str, Map, Map, ModuleRecord) -> {
<add> // context: ExpanderContext,
<add> // mod: ModuleTerm
<add> // }
<add> function expandModule(mod, filename, templateMap, patternMap, moduleRecord) {
<add> // create a new expander context for this module
<add> var context = makeModuleExpanderContext(filename,
<add> templateMap,
<add> patternMap,
<add> 0,
<add> moduleRecord);
<ide> return {
<ide> context: context,
<del> mod: collectImports(mod, context) |> mod -> {
<del> mod.imports.forEach(imp -> {
<del> var modToImport = loadImport(imp, mod, options, context);
<del>
<del> if (imp.isImport) {
<del> context = visit(modToImport, 0, context, options);
<del> } else if (imp.isImportForMacros) {
<del> context = invoke(modToImport, 1, context, options);
<del> context = visit(modToImport, 1, context, options);
<del> } else {
<del> assert(false, "not implemented yet");
<del> }
<del> var importPhase = imp.isImport ? 0 : 1;
<del> bindImportInMod(imp, mod, modToImport, context, importPhase);
<del> });
<del> return expandTermTreeToFinal(mod, context);
<del> }
<add> mod: expandTermTreeToFinal(mod, context)
<ide> };
<ide> }
<ide>
<ide>
<ide> // Takes an expanded module term and flattens it.
<ide> // @ (ModuleTerm, SweetOptions, TemplateMap, PatternMap) -> [...SyntaxObject]
<del> function flattenModule(mod, context) {
<add> function flattenModule(modTerm, modRecord, context) {
<ide>
<ide> // filter the imports to just the imports and names that are
<ide> // actually available at runtime
<del> var imports = mod.imports.reduce((acc, imp) -> {
<add> var imports = modRecord.importEntries.reduce((acc, imp) -> {
<ide> if (imp.isImportForMacros) {
<ide> return acc;
<ide> }
<ide>
<ide> // filter the exports to just the exports and names that are
<ide> // actually available at runtime
<del> var output = mod.body.reduce((acc, term) -> {
<add> var output = modTerm.body.reduce((acc, term) -> {
<ide> if (term.isExport) {
<ide> if (term.name.token.type === parser.Token.Delimiter) {
<ide> term.name = filterCompileNames(term.name, context);
<ide> assert(false, "not implemented yet");
<ide> }
<ide> }
<del> return acc.concat(term.destruct(context, {stripCompileTerm: true}));
<add> return acc.concat(term.destruct(context, {stripCompileTerm: true,
<add> stripModuleTerm: true}));
<ide> }, []);
<ide>
<ide>
<ide>
<ide> function flattenImports(imports, mod, context) {
<ide> return imports.reduce((acc, imp) -> {
<del> var modFullPath = resolvePath(unwrapSyntax(imp.from), mod);
<add> var modFullPath = resolvePath(unwrapSyntax(imp.from), context.filename);
<ide> if (availableModules.has(modFullPath)) {
<del> var flattened = flattenModule(availableModules.get(modFullPath), context);
<add> var modPair = availableModules.get(modFullPath);
<add> var flattened = flattenModule(modPair.term, modPair.record, context);
<ide> acc.push({
<ide> path: modFullPath,
<ide> code: flattened.body
<ide> var patternMap = new StringMap();
<ide> availableModules = new StringMap();
<ide>
<del> var expanded = expandModule(mod, options, templateMap, patternMap);
<del> var flattened = flattenModule(expanded.mod, expanded.context);
<add> var expanded = expandModule(mod.term, filename, templateMap, patternMap, mod.record);
<add> var flattened = flattenModule(expanded.mod, expanded.context.moduleRecord, expanded.context);
<ide>
<ide> var compiledModules = flattenImports(flattened.imports, expanded.mod, expanded.context);
<ide> return [{ |
|
Java | mit | 24a4075c8a37a4704fcc0f46515b3fcd49d7d816 | 0 | frie321984/eClipHistory | package org.schertel.friederike.ecliphistory.view;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;
import org.schertel.friederike.ecliphistory.model.ClipboardHistory;
import org.schertel.friederike.ecliphistory.model.ClipboardHistoryEntry;
import org.schertel.friederike.ecliphistory.util.LogUtility;
public class EClipHistoryViewPart extends ViewPart implements Observer {
private Label lblHistory;
private Label lblLatestEntry;
private Label lblNumberOfEntries;
private Label lblEntries;
private Button btnUpdate;
public EClipHistoryViewPart() {
// do nothing
}
@Focus
public void setFocus() {
LogUtility.debug("setFocus");
lblHistory.setFocus();
}
private void updateContent() {
lblNumberOfEntries.setText(String.format("%d", ClipboardHistory
.getInstance().size()));
lblNumberOfEntries.pack();
ClipboardHistoryEntry latestEntry = ClipboardHistory.getInstance()
.getItem(0);
lblLatestEntry.setText("");
if (latestEntry != null) {
lblLatestEntry.setText(latestEntry.content);
}
}
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
lblHistory = new Label(parent, SWT.NONE);
GridData gd_lblHistory = new GridData(SWT.FILL, SWT.CENTER, true,
false, 2, 1);
gd_lblHistory.widthHint = 442;
lblHistory.setLayoutData(gd_lblHistory);
lblHistory.setText("History");
lblEntries = new Label(parent, SWT.NONE);
lblEntries.setText("Entries: ");
lblNumberOfEntries = new Label(parent, SWT.NONE);
lblNumberOfEntries.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
true, false, 1, 1));
lblNumberOfEntries.setText("0");
lblLatestEntry = new Label(parent, SWT.NONE);
lblLatestEntry.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
false, 2, 1));
lblLatestEntry.setText("[latest entry]");
new Label(parent, SWT.NONE);
new Label(parent, SWT.NONE);
btnUpdate = new Button(parent, SWT.NONE);
btnUpdate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateContent();
}
});
btnUpdate.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
false, 2, 1));
btnUpdate.setText("Update");
ClipboardHistory.getInstance().addObserver(this);
updateContent();
}
@Override
public void update(Observable o, Object arg) {
updateContent();
}
}
| org.schertel.friederike.ecliphistory.application/src/org/schertel/friederike/ecliphistory/view/EClipHistoryViewPart.java | package org.schertel.friederike.ecliphistory.view;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;
import org.schertel.friederike.ecliphistory.model.ClipboardHistory;
import org.schertel.friederike.ecliphistory.model.ClipboardHistoryEntry;
import org.schertel.friederike.ecliphistory.util.LogUtility;
public class EClipHistoryViewPart extends ViewPart {
private Label lblHistory;
private Label lblLatestEntry;
private Label lblNumberOfEntries;
private Label lblEntries;
private Button btnUpdate;
public EClipHistoryViewPart() {
// do nothing
}
@Focus
public void setFocus() {
LogUtility.debug("setFocus");
lblHistory.setFocus();
}
private void updateContent() {
lblNumberOfEntries.setText(String.format("%d", ClipboardHistory
.getInstance().size()));
lblNumberOfEntries.pack();
ClipboardHistoryEntry latestEntry = ClipboardHistory.getInstance()
.getItem(0);
lblLatestEntry.setText("");
if (latestEntry != null) {
lblLatestEntry.setText(latestEntry.content);
}
}
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
lblHistory = new Label(parent, SWT.NONE);
GridData gd_lblHistory = new GridData(SWT.FILL, SWT.CENTER, true,
false, 2, 1);
gd_lblHistory.widthHint = 442;
lblHistory.setLayoutData(gd_lblHistory);
lblHistory.setText("History");
lblEntries = new Label(parent, SWT.NONE);
lblEntries.setText("Entries: ");
lblNumberOfEntries = new Label(parent, SWT.NONE);
lblNumberOfEntries.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
true, false, 1, 1));
lblNumberOfEntries.setText("0");
lblLatestEntry = new Label(parent, SWT.NONE);
lblLatestEntry.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
false, 2, 1));
lblLatestEntry.setText("[latest entry]");
new Label(parent, SWT.NONE);
new Label(parent, SWT.NONE);
btnUpdate = new Button(parent, SWT.NONE);
btnUpdate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateContent();
}
});
btnUpdate.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
false, 2, 1));
btnUpdate.setText("Update");
updateContent();
}
}
| Änderungen an der History werden automatisch im View aktualisiert. | org.schertel.friederike.ecliphistory.application/src/org/schertel/friederike/ecliphistory/view/EClipHistoryViewPart.java | Änderungen an der History werden automatisch im View aktualisiert. | <ide><path>rg.schertel.friederike.ecliphistory.application/src/org/schertel/friederike/ecliphistory/view/EClipHistoryViewPart.java
<ide> package org.schertel.friederike.ecliphistory.view;
<add>
<add>import java.util.Observable;
<add>import java.util.Observer;
<ide>
<ide> import org.eclipse.e4.ui.di.Focus;
<ide> import org.eclipse.swt.SWT;
<ide> import org.schertel.friederike.ecliphistory.model.ClipboardHistoryEntry;
<ide> import org.schertel.friederike.ecliphistory.util.LogUtility;
<ide>
<del>public class EClipHistoryViewPart extends ViewPart {
<add>public class EClipHistoryViewPart extends ViewPart implements Observer {
<ide>
<ide> private Label lblHistory;
<ide> private Label lblLatestEntry;
<ide> btnUpdate.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
<ide> false, 2, 1));
<ide> btnUpdate.setText("Update");
<add>
<add> ClipboardHistory.getInstance().addObserver(this);
<ide>
<ide> updateContent();
<ide> }
<ide>
<add> @Override
<add> public void update(Observable o, Object arg) {
<add> updateContent();
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 2f6ad7e045dce28aab94ef1e10581600621a24d8 | 0 | WolfgangFahl/Mediawiki-Japi,WolfgangFahl/Mediawiki-Japi | /**
*
* This file is part of the https://github.com/WolfgangFahl/Mediawiki-Japi open source project
*
* Copyright 2015-2017 BITPlan GmbH https://github.com/BITPlan
*
* 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.bitplan.mediawiki.japi;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Level;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import com.bitplan.mediawiki.japi.api.Api;
import com.bitplan.mediawiki.japi.api.Bl;
import com.bitplan.mediawiki.japi.api.Delete;
import com.bitplan.mediawiki.japi.api.Edit;
import com.bitplan.mediawiki.japi.api.General;
import com.bitplan.mediawiki.japi.api.Ii;
import com.bitplan.mediawiki.japi.api.Im;
import com.bitplan.mediawiki.japi.api.Imageinfo;
import com.bitplan.mediawiki.japi.api.Img;
import com.bitplan.mediawiki.japi.api.Iu;
import com.bitplan.mediawiki.japi.api.Login;
import com.bitplan.mediawiki.japi.api.P;
import com.bitplan.mediawiki.japi.api.Page;
import com.bitplan.mediawiki.japi.api.Parse;
import com.bitplan.mediawiki.japi.api.Query;
import com.bitplan.mediawiki.japi.api.Rc;
import com.bitplan.mediawiki.japi.api.S;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.StreamDataBodyPart;
/**
* access to Mediawiki api
*
* @author wf
*
*/
public class Mediawiki extends MediaWikiApiImpl implements MediawikiApi {
/**
* current Version
*/
protected static final String VERSION = "0.0.19";
/**
* if true main can be called without calling system.exit() when finished
*/
public static boolean testMode = false;
/**
* see <a href=
* 'https://www.mediawiki.org/wiki/API:Main_page#Identifying_your_client'>
* Iden t i f y i n g your client:User-Agent</a>
*/
protected static final String USER_AGENT = "Mediawiki-Japi/" + VERSION
+ " (https://github.com/WolfgangFahl/Mediawiki-Japi; [email protected])";
/**
* default script path
*/
public static final String DEFAULT_SCRIPTPATH = "/w";
protected String siteurl;
protected String scriptPath = DEFAULT_SCRIPTPATH;
// FIXME - default should be json soon
protected String format = "xml";
protected String apiPath = "/api.php?";
// the client and it's cookies
private Client client;
private ArrayList<Object> cookies;
// mediaWikiVersion and site info
protected String userid;
SiteInfo siteinfo;
// Json unmarshaller
private Gson gson;
/**
* enable debugging
*
* @param debug
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
@Override
public boolean isDebug() {
return this.debug;
}
/**
* @return the siteurl
*/
public String getSiteurl() {
return siteurl;
}
/**
* @param siteurl
* the siteurl to set
*/
public void setSiteurl(String siteurl) {
this.siteurl = siteurl;
}
/**
* @return the scriptPath
*/
public String getScriptPath() {
return scriptPath;
}
/**
* @param scriptPath
* the scriptPath to set
*/
public void setScriptPath(String scriptPath) {
this.scriptPath = scriptPath;
}
/**
* construct me with no siteurl set
*
* @throws Exception
*/
public Mediawiki() throws Exception {
this(null);
}
/**
* construct a Mediawiki for the given url using the default Script path
*
* @param siteurl
* - the url to use
* @throws Exception
*/
public Mediawiki(String siteurl) throws Exception {
this(siteurl, DEFAULT_SCRIPTPATH);
}
/**
* construct a Mediawiki for the given url and scriptpath
*
* @param siteurl
* - the url to use
* @param pScriptPath
* - the scriptpath to use
* @throws Exception
*/
public Mediawiki(String siteurl, String pScriptPath) throws Exception {
init(siteurl, pScriptPath);
}
/**
* overrideable e.g for SSL configuration
*
* @throws Exception
*/
@Override
public void init(String siteurl, String scriptpath) throws Exception {
ApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
config.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES,
true);
client = ApacheHttpClient.create(config);
client.setFollowRedirects(true);
// org.apache.log4j.Logger.getLogger("httpclient").setLevel(Level.ERROR);
this.siteurl = siteurl;
this.scriptPath = scriptpath;
}
/**
* get a current IsoTimeStamp
*
* @return - the current timestamp
*/
public String getIsoTimeStamp() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
/**
* get a String from a given URL
*
* @param urlString
* @return
*/
public static String getStringFromUrl(String urlString) {
ApacheHttpClient lclient = ApacheHttpClient.create();
WebResource webResource = lclient.resource(urlString);
ClientResponse response = webResource.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("HTTP error code : " + response.getStatus());
}
String result = response.getEntity(String.class);
return result;
}
/**
* get the given Builder for the given queryUrl this is a wrapper to be able
* to debug all QueryUrl
*
* @param queryUrl
* - either a relative or absolute path
* @return
* @throws Exception
*/
public Builder getResource(String queryUrl) throws Exception {
if (debug)
LOGGER.log(Level.INFO, queryUrl);
WebResource wrs = client.resource(queryUrl);
Builder result = wrs.header("USER-AGENT", USER_AGENT);
return result;
}
/**
* get a Post response
*
* @param queryUrl
* @param params
* - direct query parameters
* @param token
* - a token if any
* @param pFormData
* - the form data - either as multipart of urlencoded
* @return - the client Response
* @throws Exception
*/
public ClientResponse getPostResponse(String queryUrl, String params,
TokenResult token, Object pFormDataObject) throws Exception {
params = params.replace("|", "%7C");
// modal handling of post
FormDataMultiPart form = null;
MultivaluedMap<String, String> lFormData = null;
if (pFormDataObject instanceof FormDataMultiPart) {
form = (FormDataMultiPart) pFormDataObject;
} else {
@SuppressWarnings("unchecked")
Map<String, String> pFormData = (Map<String, String>) pFormDataObject;
lFormData = new MultivaluedMapImpl();
if (pFormData != null) {
for (String key : pFormData.keySet()) {
lFormData.add(key, pFormData.get(key));
}
}
}
if (token != null) {
switch (token.tokenMode) {
case token1_24:
if (lFormData != null) {
lFormData.add(token.tokenName, token.token);
} else {
form.field(token.tokenName, token.token);
}
break;
default:
params += token.asParam();
}
}
Builder resource = getResource(queryUrl + params);
// FIXME allow to specify content type (not needed for Mediawiki itself
// but
// could be good for interfacing )
ClientResponse response = null;
if (lFormData != null) {
response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, lFormData);
} else {
response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, form);
}
return response;
}
public enum Method {
Post, Get, Head, Put
};
/**
* get a response for the given url and method
*
* @param url
* @param method
* @return
* @throws Exception
*/
public ClientResponse getResponse(String url, Method method)
throws Exception {
Builder resource = getResource(url);
ClientResponse response = null;
switch (method) {
case Get:
response = resource.get(ClientResponse.class);
break;
case Post:
response = resource.post(ClientResponse.class);
break;
case Head:
response = resource.head();
break;
case Put:
response = resource.put(ClientResponse.class);
break;
}
return response;
}
/**
* get the Response string
*
* @param response
* @return the String representation of a response
* @throws Exception
*/
public String getResponseString(ClientResponse response) throws Exception {
if (debug)
LOGGER.log(Level.INFO, "status: " + response.getStatus());
String responseText = response.getEntity(String.class);
if (response.getStatus() != 200) {
handleError("status " + response.getStatus() + ":'" + responseText + "'");
}
return responseText;
}
/**
* get a Map of parameter from a & delimited parameter list
*
* @param params
* - the list of parameters
* @return the map FIXME - should check that split creates and even number of
* entries - add test case for this
*/
public Map<String, String> getParamMap(String params) {
Map<String, String> result = new HashMap<String, String>();
String[] paramlist = params.split("&");
for (int i = 0; i < paramlist.length; i++) {
String[] parts = paramlist[i].split("=");
if (parts.length == 2)
result.put(parts[0], parts[1]);
}
return result;
}
/**
* get the action result for the given parameters
*
* @param action
* @param params
* @param token
* @param pFormData
* @param format
* - json or xml
* @return the String e.g. xml or json
* @throws Exception
*/
public String getActionResultText(String action, String params, TokenResult token,
Object pFormData, String format) throws Exception {
String queryUrl = siteurl + scriptPath + apiPath + "&action=" + action
+ "&format=" + format;
ClientResponse response;
// decide for the method to use for api access
response = this.getPostResponse(queryUrl, params, token, pFormData);
String text = this.getResponseString(response);
return text;
}
/**
* get the result for the given action and params
*
* @param action
* @param params
* @param token
* (may be null)
* @param formData
* (may be null)
* @format - the format to use e.g. json or xml
* @return the API result for the action
* @throws Exception
*/
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData, String format) throws Exception {
String text = this.getActionResultText(action, params, token, pFormData,
format);
Api api = null;
if ("xml".equals(format)) {
if (debug) {
// convert the xml to a more readable format
String xmlDebug = text.replace(">", ">\n");
LOGGER.log(Level.INFO, xmlDebug);
}
if (text.startsWith("<?xml version"))
api = fromXML(text);
else {
LOGGER.log(Level.SEVERE, text);
throw new Exception("invalid xml:"+text);
}
} else if ("json".equals(format)) {
if (gson==null)
gson=new Gson();
api=gson.fromJson(text, Api.class);
} else {
throw new IllegalStateException("unknown format " + format);
}
return api;
}
/**
* get the action result for the default format
* @param action
* @param params
* @param token
* @param pFormData
* @return - the action result
* @throws Exception
*/
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData) throws Exception {
return getActionResult(action, params, token, pFormData, format);
}
/**
* get the result for the given action and query
*
* @param action
* @param params
* @return the API result for the action
* @throws Exception
*/
public Api getActionResult(String action, String params) throws Exception {
Api result = this.getActionResult(action, params, null, null);
return result;
}
/**
* get the Result for the given query
*
* @param query
* @return the API result for the query
* @throws Exception
*/
public Api getQueryResult(String query) throws Exception {
Api result = this.getActionResult("query", query, null, null);
return result;
}
/**
* get a normalized | delimited (encoded as %7C) string of titles
*
* @param examplePages
* - the list of pages to get the titles for
* @return a string with all the titles e.g. Main%20Page%7CSome%20Page
* @throws Exception
*/
public String getTitles(List<String> titleList) throws Exception {
String titles = "";
String delim = "";
for (String title : titleList) {
titles = titles + delim + normalizeTitle(title);
delim = "%7C";
}
return titles;
}
/**
* get the siteinfo
*
* @return the siteinfo
* @throws Exception
*/
public SiteInfo getSiteInfo() throws Exception {
if (siteinfo == null) {
Api api = getQueryResult("&meta=siteinfo&siprop=general%7Cnamespaces");
Query query = api.getQuery();
setUpSiteInfo(query);
}
return siteinfo;
}
/**
* setup siteinfo for a query (e.g. for testing)
*
* @param query
*/
public void setUpSiteInfo(Query query) {
General general = query.getGeneral();
siteinfo = new SiteInfoImpl(general, query.getNamespaces());
}
/**
* check whether this is MediaWiki 1.28 or higher but make sure getVersion
* calls with readapidenied are ignored see
* https://github.com/WolfgangFahl/Mediawiki-Japi/issues/32
*
* @return
*/
public boolean isVersion128() {
String mwversion = "Mediawiki 1.27 or before";
try {
mwversion = this.getVersion();
} catch (Exception e) {
LOGGER.log(Level.INFO,
"Could not retrieve Mediawiki Version via API - will assume "
+ mwversion
+ " you might want to set the Version actively if you are on 1.28 and have the api blocked for non-logged in users");
}
boolean result = mwversion.compareToIgnoreCase("Mediawiki 1.28") >= 0;
return result;
}
/**
* prepare the login by getting the login token
*
* @param username
* @return the ApiResult
* @throws Exception
*/
public TokenResult prepareLogin(String username) throws Exception {
username = encode(username);
Api apiResult = null;
TokenResult token = new TokenResult();
token.tokenName = "lgtoken";
token.tokenMode = TokenMode.token1_19;
// see https://github.com/WolfgangFahl/Mediawiki-Japi/issues/31
if (this.isVersion128()) {
apiResult = this.getQueryResult("&meta=tokens&type=login");
super.handleError(apiResult);
token.token = apiResult.getQuery().getTokens().getLogintoken();
} else {
apiResult = getActionResult("login", "&lgname=" + username, null, null);
super.handleError(apiResult);
Login login = apiResult.getLogin();
token.token = login.getToken();
}
return token;
}
/**
* second step of login process
*
* @param token
* @param username
* @param password
* @return
* @throws Exception
*/
public Login login(TokenResult token, String username, String password)
throws Exception {
return login(token, username, password, null);
}
/**
* second step of login process
*
* @param token
* @param username
* @param password
* @param domain
* @return
* @throws Exception
*/
public Login login(TokenResult token, String username, String password,
String domain) throws Exception {
username = encode(username);
if (domain != null) {
domain = encode(domain);
}
Api apiResult = null;
// depends on MediaWiki version see
// https://test2.wikipedia.org/w/api.php?action=help&modules=clientlogin
if (this.isVersion128()) {
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("lgpassword", password);
lFormData.put("lgtoken", token.token);
if (domain != null) {
apiResult = getActionResult("login",
"&lgdomain=" + domain + "&lgname=" + username, null, lFormData);
} else {
apiResult = getActionResult("login", "&lgname=" + username, null,
lFormData);
}
// apiResult = getActionResult("clientlogin", "&lgname=" +
// username+"&loginreturnurl="+this.siteurl, null, lFormData);
} else {
password = encode(password);
if (domain != null) {
apiResult = getActionResult("login", "&lgdomain=" + domain + "&lgname="
+ username + "&lgpassword=" + password, token, null);
} else {
apiResult = getActionResult("login",
"&lgname=" + username + "&lgpassword=" + password, token, null);
}
}
Login login = apiResult.getLogin();
userid = login.getLguserid();
return login;
}
/**
* login with the given username, password and domain
*
* @param username
* @param password
* @param domain
* @return Login
* @throws Exception
*/
public Login login(String username, String password, String domain)
throws Exception {
// login is a two step process
// first we get a token
TokenResult token = prepareLogin(username);
// and then with the token we login using the password
Login login = login(token, username, password, domain);
return login;
}
/**
* login with the given username and password
*
* @param username
* @param password
* @return Login
* @throws Exception
*/
public Login login(String username, String password) throws Exception {
return login(username, password, null);
}
@Override
public boolean isLoggedIn() {
boolean result = userid != null;
return result;
}
/**
* end the session
*
* @throws Exception
*/
public void logout() throws Exception {
Api apiResult = getActionResult("logout", "", null, null);
if (apiResult != null) {
userid = null;
// FIXME check apiResult
}
if (cookies != null) {
cookies.clear();
cookies = null;
}
}
/**
* get the page Content for the given page Title
*
* @param pageTitle
* @param queryParams
* - extra query params e.g. for sections
* @param checkNotNull
* - check if the content should not be null
* @return the page Content
* @throws Exception
*/
public String getPageContent(String pageTitle, String queryParams,
boolean checkNotNull) throws Exception {
Api api = getQueryResult("&prop=revisions&rvprop=content" + queryParams
+ "&titles=" + normalizeTitle(pageTitle));
handleError(api);
List<Page> pages = api.getQuery().getPages();
String content = null;
if (pages != null) {
Page page = pages.get(0);
if (page != null) {
if (page.getRevisions().size() > 0) {
content = page.getRevisions().get(0).getValue();
}
}
}
if (checkNotNull && content == null) {
String errMsg = "pageTitle '" + pageTitle + "' not found";
this.handleError(errMsg);
}
return content;
}
/**
* get the page Content for the given page Title
*
* @param pageTitle
* @return the page Content
* @throws Exception
*/
public String getPageContent(String pageTitle) throws Exception {
String result = this.getPageContent(pageTitle, "", false);
return result;
}
/**
* get the text for the given section
*
* @param pageTitle
* @param sectionNumber
* @return
* @throws Exception
*/
public String getSectionText(String pageTitle, int sectionNumber)
throws Exception {
String result = this.getPageContent(pageTitle,
"&rvsection=" + sectionNumber, false);
return result;
}
@Override
public List<S> getSections(String pageTitle) throws Exception {
String params = "&prop=sections&page=" + pageTitle;
Parse parse = getParse(params);
List<S> sections = parse.getSections();
return sections;
}
@Override
public String getPageHtml(String pageTitle) throws Exception {
String params = "&page=" + encode(pageTitle);
Parse parse = getParse(params);
String html = parse.getText();
return html;
}
/**
* get the parse Result for the given params
*
* @param params
* @return the Parse Result
* @throws Exception
*/
public Parse getParse(String params) throws Exception {
String action = "parse";
Api api = getActionResult(action, params);
super.handleError(api);
return api.getParse();
}
/**
* get a list of pages for the given titles see
* <a href='http://www.mediawiki.org/wiki/API:Query'>API:Query</a>
*
* @param titleList
* @param rvprop
* - the revision properties
* @return the list of pages retrieved
* @throws Exception
*
* FIXME should be part of the Java Interface
*/
public List<Page> getPages(List<String> titleList, String rvprop)
throws Exception {
String titles = this.getTitles(titleList);
// https://www.mediawiki.org/wiki/API:Revisions#Parameters
Api api = getQueryResult(
"&titles=" + titles + "&prop=revisions&rvprop=" + rvprop);
handleError(api);
Query query = api.getQuery();
if (query == null) {
throw new Exception("query is null for getPages '" + titleList
+ "' rvprop='" + rvprop + "'");
}
List<Page> pages = query.getPages();
return pages;
}
/**
* get a list of pages for the given titles see
* <a href='http://www.mediawiki.org/wiki/API:Query'>API:Query</a>
*
* @param titleList
* @return
* @throws Exception
*/
public List<Page> getPages(List<String> titleList) throws Exception {
String rvprop = "content|ids|timestamp";
List<Page> result = this.getPages(titleList, rvprop);
return result;
}
/**
* the different modes of handling tokens - depending on MediaWiki version
*/
enum TokenMode {
token1_19, token1_20_23, token1_24
}
/**
* helper class to handle the different token modes
*
* @author wf
*
*/
class TokenResult {
String tokenName;
String token;
TokenMode tokenMode;
/**
* set my token - remove trailing backslash or +\ if necessary
*
* @param pToken
* - the token to set
*/
public void setToken(String pToken) {
token = pToken;
}
/**
* get me as a param string e.g. &lgtoken=1234 make sure the trailing \ or
* +\ are handled correctly see
* <a href= 'https://www.mediawiki.org/wiki/Manual:Edit_token'>Manual:
* Edit_token</a>
*
* @return - the resulting string
* @throws Exception
*/
public String asParam() throws Exception {
String lToken = token;
/*
* switch (tokenMode) { case token1_24: lToken=lToken.replace("+","");
* lToken=lToken.replace("\\",""); break; default:
*
* }
*/
// token=pToken+"%2B%5C";
// http://wikimedia.7.x6.nabble.com/Error-badtoken-Info-Invalid-token-td4977853.html
String result = "&" + tokenName + "=" + encode(lToken);
if (debug)
LOGGER.log(Level.INFO, "token " + token + "=>" + result);
return result;
}
}
/**
* get an edit token for the given page Title see
* <a href='https://www.mediawiki.org/wiki/API:Tokens'>API:Tokens</a>
*
* @param pageTitle
* @param type
* e.g. edit or delete
* @return the edit token for the page title
* @throws Exception
*/
public TokenResult getEditToken(String pageTitle, String type)
throws Exception {
pageTitle = normalizeTitle(pageTitle);
String editversion = "";
String action = "query";
String params = "&meta=tokens";
TokenMode tokenMode;
if (getVersion().compareToIgnoreCase("Mediawiki 1.24") >= 0) {
editversion = "Versions 1.24 and later";
tokenMode = TokenMode.token1_24;
params = "&meta=tokens";
} else if (getVersion().compareToIgnoreCase("Mediawiki 1.20") >= 0) {
editversion = "Versions 1.20-1.23";
tokenMode = TokenMode.token1_20_23;
action = "tokens";
params = "&type=" + type;
} else {
editversion = "Version 1.19 and earlier";
tokenMode = TokenMode.token1_19;
params = "&prop=info&7Crevisions&intoken=" + type + "&titles="
+ pageTitle;
}
if (debug) {
LOGGER.log(Level.INFO,
"handling " + type + " token for wiki version " + getVersion()
+ " as " + editversion + " with action=" + action + params);
}
Api api = getActionResult(action, params);
handleError(api);
TokenResult token = new TokenResult();
token.tokenMode = tokenMode;
token.tokenName = "token";
switch (tokenMode) {
case token1_19:
Page page = api.getQuery().getPages().get(0);
if (type.equals("edit")) {
token.setToken(page.getEdittoken());
} else if (type.equals("delete")) {
token.setToken(page.getDeletetoken());
}
break;
case token1_20_23:
if (type.equals("edit")) {
token.setToken(api.getTokens().getEdittoken());
} else if (type.equals("delete")) {
token.setToken(api.getTokens().getDeletetoken());
}
break;
default:
token.setToken(api.getQuery().getTokens().getCsrftoken());
break;
}
return token;
}
/**
* https://www.mediawiki.org/wiki/API:Edit
*/
@Override
public Edit edit(String pageTitle, String text, String summary)
throws Exception {
Edit result = this.edit(pageTitle, text, summary, true, false, -2, null,
null);
return result;
}
/**
* https://www.mediawiki.org/wiki/API:Delete/de
*
* @return info
*/
@Override
public Delete delete(String pageTitle, String reason) throws Exception {
Delete result = new Delete();
String pageContent = getPageContent(pageTitle);
if (pageContent != null && pageContent.contains(protectionMarker)) {
LOGGER.log(Level.WARNING, "page " + pageTitle + " is protected!");
} else {
TokenResult token = getEditToken(pageTitle, "delete");
if (token.token == null) {
throw new IllegalStateException(
"could not get " + token.tokenMode.toString() + " delete token for "
+ pageTitle + " ");
}
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("title", pageTitle);
lFormData.put("reason", reason);
String params = "";
Api api = this.getActionResult("delete", params, token, lFormData);
handleError(api);
result = api.getDelete();
}
return result;
}
@Override
public Edit edit(String pageTitle, String text, String summary, boolean minor,
boolean bot, int sectionNumber, String sectionTitle, Calendar basetime)
throws Exception {
Edit result = new Edit();
String pageContent = getPageContent(pageTitle);
if (pageContent != null && pageContent.contains(protectionMarker)) {
LOGGER.log(Level.WARNING, "page " + pageTitle + " is protected!");
} else {
TokenResult token = getEditToken(pageTitle, "edit");
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("text", text);
lFormData.put("title", pageTitle);
lFormData.put("summary", summary);
if (minor)
lFormData.put("minor", "1");
if (bot)
lFormData.put("bot", "1");
switch (sectionNumber) {
case -1:
lFormData.put("section", "new");
if (sectionTitle != null)
lFormData.put("sectiontitle", sectionTitle);
break;
case -2:
break;
default:
lFormData.put("section", "" + sectionNumber);
break;
}
String params = "";
Api api = this.getActionResult("edit", params, token, lFormData);
handleError(api);
result = api.getEdit();
}
return result;
}
/**
* https://www.mediawiki.org/wiki/API:Upload
*/
@Override
public synchronized void upload(File fileToUpload, String filename,
String contents, String comment) throws Exception {
this.upload(new FileInputStream(fileToUpload), filename, contents, comment);
}
/**
* upload from the given inputstream
*
* @param fileToUpload
* @param filename
* @param contents
* @param comment
* @throws Exception
*/
public synchronized void upload(InputStream fileToUpload, String filename,
String contents, String comment) throws Exception {
TokenResult token = getEditToken("File:" + filename, "edit");
final FormDataMultiPart multiPart = new FormDataMultiPart();
// http://stackoverflow.com/questions/5772225/trying-to-upload-a-file-to-a-jax-rs-jersey-server
multiPart.bodyPart(new StreamDataBodyPart("file", fileToUpload));
multiPart.field("filename", filename);
multiPart.field("ignorewarnings", "true");
multiPart.field("text", contents);
if (!comment.isEmpty())
multiPart.field("comment", comment);
String params = "";
Api api = this.getActionResult("upload", params, token, multiPart);
handleError(api);
}
@Override
public void upload(Ii ii, String fileName, String pageContent)
throws Exception {
String url = ii.getUrl();
InputStream imageInput = new URL(url).openStream();
String comment = ii.getComment();
this.upload(imageInput, fileName, pageContent, comment);
}
/**
* getAllPages
*
* @param apfrom
* - may be null or empty
* @param aplimit
* @return
* @throws Exception
*/
public List<P> getAllPages(String apfrom, int aplimit) throws Exception {
String query = "&list=allpages";
if (apfrom != null && !apfrom.trim().equals("")) {
query += "&apfrom=" + apfrom;
}
query += "&aplimit=" + aplimit;
Api api = getQueryResult(query);
List<P> pageRefList = api.getQuery().getAllpages();
return pageRefList;
}
@Override
public List<Img> getAllImagesByTimeStamp(String aistart, String aiend,
int ailimit) throws Exception {
String query = "&list=allimages&aisort=timestamp";
if (aistart != null && !aistart.trim().equals("")) {
query += "&aistart=" + aistart;
}
if (aiend != null && !aiend.trim().equals("")) {
query += "&aiend=" + aiend;
}
query += "&ailimit=" + ailimit;
Api api = getQueryResult(query);
handleError(api);
List<Img> result = api.getQuery().getAllImages();
return result;
}
@Override
public List<Bl> getBacklinks(String pageTitle, String params, int bllimit)
throws Exception {
String query = "&list=backlinks&bltitle=" + normalizeTitle(pageTitle);
query += "&bllimit=" + bllimit;
query += params;
Api api = getQueryResult(query);
handleError(api);
List<Bl> result = api.getQuery().getBacklinks();
return result;
}
@Override
public List<Iu> getImageUsage(String imageTitle, String params, int limit)
throws Exception {
String query = "&list=imageusage&iutitle=" + normalizeTitle(imageTitle);
query += "&iulimit=" + limit;
query += params;
Api api = getQueryResult(query);
handleError(api);
List<Iu> result = api.getQuery().getImageusage();
return result;
}
/**
* handle the given Throwable (in commandline mode)
*
* @param t
*/
public void handle(Throwable t) {
System.out.flush();
System.err.println(t.getClass().getSimpleName() + ":" + t.getMessage());
if (debug)
t.printStackTrace();
}
/**
* show the Version
*/
public static void showVersion() {
System.err.println("Mediawiki-Japi Version: " + VERSION);
System.err.println();
System.err
.println(" github: https://github.com/WolfgangFahl/Mediawiki-Japi");
System.err.println("");
}
/**
* show a usage
*/
public void usage(String msg) {
System.err.println(msg);
showVersion();
System.err.println(" usage: java com.bitplan.mediawiki.japi.Mediawiki");
parser.printUsage(System.err);
exitCode = 1;
}
/**
* show Help
*/
public void showHelp() {
String msg = "Help\n" + "Mediawiki-Japi version " + VERSION
+ " has no functional command line interface\n"
+ "Please visit http://mediawiki-japi.bitplan.com for usage instructions";
usage(msg);
}
private CmdLineParser parser;
static int exitCode;
/**
* set to true for debugging
*/
@Option(name = "-d", aliases = {
"--debug" }, usage = "debug\nadds debugging output")
protected boolean debug = false;
@Option(name = "-h", aliases = { "--help" }, usage = "help\nshow this usage")
boolean showHelp = false;
@Option(name = "-v", aliases = {
"--version" }, usage = "showVersion\nshow current version if this switch is used")
boolean showVersion = false;
/**
* main instance - this is the non-static version of main - it will run as a
* static main would but return it's exitCode to the static main the static
* main will then decide whether to do a System.exit(exitCode) or not.
*
* @param args
* - command line arguments
* @return - the exit Code to be used by the static main program
*/
protected int maininstance(String[] args) {
parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (debug)
showVersion();
if (this.showVersion) {
showVersion();
} else if (this.showHelp) {
showHelp();
} else {
// FIXME - do something
// implement actions
System.err.println(
"Commandline interface is not functional in " + VERSION + " yet");
exitCode = 1;
// exitCode = 0;
}
} catch (CmdLineException e) {
// handling of wrong arguments
usage(e.getMessage());
} catch (Exception e) {
handle(e);
exitCode = 1;
}
return exitCode;
}
/**
* entry point e.g. for java -jar called provides a command line interface
*
* @param args
*/
public static void main(String args[]) {
Mediawiki wiki;
try {
wiki = new Mediawiki();
int result = wiki.maininstance(args);
if (!testMode && result != 0)
System.exit(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* create the given user account
*
* @param name
* @param eMail
* @param realname
* @param mailpassword
* @param reason
* @param language
* @throws Exception
*/
public Api createAccount(String name, String eMail, String realname,
boolean mailpassword, String reason, String language) throws Exception {
String params = "&name=" + name;
params += "&email=" + eMail;
params += "&realname=" + realname;
params += "&mailpassword=" + mailpassword;
params += "&reason=" + reason;
params += "&token=";
Api api = getActionResult("createaccount", params);
handleError(api);
String token = api.getCreateaccount().getToken();
params += token;
api = getActionResult("createaccount", params);
return api;
}
@Override
public Ii getImageInfo(String pageTitle) throws Exception {
// example
// https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=imageinfo&format=xml&iiprop=timestamp|user|userid|comment|parsedcomment|canonicaltitle|url|size|dimensions|sha1|mime|thumbmime|mediatype|metadata|commonmetadata|extmetadata|archivename|bitdepth|uploadwarning&titles=File%3AAlbert%20Einstein%20Head.jpg
String props = "timestamp";
props += "%7Cuser%7Cuserid%7Ccomment%7Cparsedcomment%7Curl%7Csize%7Cdimensions";
props += "%7Csha1%7Cmime%7Cthumbmime%7Cmediatype%7Carchivename%7Cbitdepth";
Api api = getQueryResult("&prop=imageinfo&iiprop=" + props + "&titles="
+ normalizeTitle(pageTitle));
handleError(api);
Ii ii = null;
List<Page> pages = api.getQuery().getPages();
if (pages != null) {
Page page = pages.get(0);
if (page != null) {
Imageinfo imageinfo = page.getImageinfo();
if (imageinfo != null) {
ii = imageinfo.getIi();
} else {
String errMsg = "imageinfo for pageTitle '" + pageTitle
+ "' not found";
this.handleError(errMsg);
}
}
}
if (ii == null) {
String errMsg = "pageTitle '" + pageTitle + "' not found";
this.handleError(errMsg);
}
return ii;
}
@Override
public List<Im> getImagesOnPage(String pageTitle, int imLimit)
throws Exception {
String query = "&titles=" + normalizeTitle(pageTitle)
+ "&prop=images&imlimit=" + imLimit;
Api api = getQueryResult(query);
handleError(api);
List<Im> result = new ArrayList<Im>();
Query lquery = api.getQuery();
if (lquery != null) {
List<Page> pages = lquery.getPages();
if (pages.size() > 0) {
Page page = pages.get(0);
result = page.getImages();
}
}
return result;
}
@Override
public List<Ii> getImageInfosForPage(String pageTitle, int imLimit)
throws Exception {
List<Im> images = this.getImagesOnPage(pageTitle, imLimit);
List<Ii> result = new ArrayList<Ii>();
for (Im image : images) {
Ii imageinfo = this.getImageInfo(image.getTitle());
if (imageinfo.getCanonicaltitle() == null) {
imageinfo.setCanonicaltitle(image.getTitle());
}
result.add(imageinfo);
}
return result;
}
/**
* get the recent changes see https://www.mediawiki.org/wiki/API:RecentChanges
*
* @param rcstart
* The timestamp to start listing from (May not be more than
* $wgRCMaxAge into the past, which on Wikimedia wikis is 30 days[1])
* @param rcend
* @param rclimit
* @return - the list of recent changes
* @throws Exception
*/
public List<Rc> getRecentChanges(String rcstart, String rcend,
Integer rclimit) throws Exception {
String query = "&list=recentchanges&rcprop=title%7Ctimestamp%7Csha1%7Cids%7Csizes%7Cflags%7Cuser";
if (rclimit != null) {
query += "&rclimit=" + rclimit;
}
if (rcstart != null) {
query += "&rcstart=" + rcstart;
}
if (rcend != null) {
query += "&rcend=" + rcend;
}
Api api = getQueryResult(query);
handleError(api);
List<Rc> rcList = api.getQuery().getRecentchanges();
rcList = sortByTitleAndFilterDoubles(rcList);
return rcList;
}
/**
* sort the given List by title and filter double titles
*
* @param rcList
* @return
*/
public List<Rc> sortByTitleAndFilterDoubles(List<Rc> rcList) {
List<Rc> result = new ArrayList<Rc>();
List<Rc> sorted = new ArrayList<Rc>();
sorted.addAll(rcList);
Collections.sort(sorted, new Comparator<Rc>() {
@Override
public int compare(Rc lRc, Rc rRc) {
int result = lRc.getTitle().compareTo(rRc.getTitle());
if (result == 0) {
result = rRc.getTimestamp().compare(lRc.getTimestamp());
}
return result;
}
});
Rc previous = null;
for (Rc rc : sorted) {
if (previous == null || (!rc.getTitle().equals(previous.getTitle()))) {
result.add(rc);
}
previous = rc;
}
Collections.sort(result, new Comparator<Rc>() {
@Override
public int compare(Rc lRc, Rc rRc) {
int result = rRc.getTimestamp().compare(lRc.getTimestamp());
return result;
}
});
return result;
}
/**
* convert a data to a MediaWiki API timestamp
*
* @param date
* @return
*/
public String dateToMWTimeStamp(Date date) {
SimpleDateFormat mwTimeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String result = mwTimeStampFormat.format(date);
return result;
}
/**
* get the most recent changes
*
* @param days
* @param rcLimit
* @return
* @throws Exception
*/
public List<Rc> getMostRecentChanges(int days, int rcLimit) throws Exception {
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -days);
Date date30daysbefore = cal.getTime();
String rcstart = dateToMWTimeStamp(today);
String rcend = dateToMWTimeStamp(date30daysbefore);
List<Rc> rcList = this.getRecentChanges(rcstart, rcend, rcLimit);
List<Rc> result = this.sortByTitleAndFilterDoubles(rcList);
return result;
}
}
| src/main/java/com/bitplan/mediawiki/japi/Mediawiki.java | /**
*
* This file is part of the https://github.com/WolfgangFahl/Mediawiki-Japi open source project
*
* Copyright 2015-2017 BITPlan GmbH https://github.com/BITPlan
*
* 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.bitplan.mediawiki.japi;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Level;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import com.bitplan.mediawiki.japi.api.Api;
import com.bitplan.mediawiki.japi.api.Bl;
import com.bitplan.mediawiki.japi.api.Delete;
import com.bitplan.mediawiki.japi.api.Edit;
import com.bitplan.mediawiki.japi.api.General;
import com.bitplan.mediawiki.japi.api.Ii;
import com.bitplan.mediawiki.japi.api.Im;
import com.bitplan.mediawiki.japi.api.Imageinfo;
import com.bitplan.mediawiki.japi.api.Img;
import com.bitplan.mediawiki.japi.api.Iu;
import com.bitplan.mediawiki.japi.api.Login;
import com.bitplan.mediawiki.japi.api.P;
import com.bitplan.mediawiki.japi.api.Page;
import com.bitplan.mediawiki.japi.api.Parse;
import com.bitplan.mediawiki.japi.api.Query;
import com.bitplan.mediawiki.japi.api.Rc;
import com.bitplan.mediawiki.japi.api.S;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.StreamDataBodyPart;
/**
* access to Mediawiki api
*
* @author wf
*
*/
public class Mediawiki extends MediaWikiApiImpl implements MediawikiApi {
/**
* current Version
*/
protected static final String VERSION = "0.0.19";
/**
* if true main can be called without calling system.exit() when finished
*/
public static boolean testMode = false;
/**
* see <a href=
* 'https://www.mediawiki.org/wiki/API:Main_page#Identifying_your_client'>
* Iden t i f y i n g your client:User-Agent</a>
*/
protected static final String USER_AGENT = "Mediawiki-Japi/" + VERSION
+ " (https://github.com/WolfgangFahl/Mediawiki-Japi; [email protected])";
/**
* default script path
*/
public static final String DEFAULT_SCRIPTPATH = "/w";
protected String siteurl;
protected String scriptPath = DEFAULT_SCRIPTPATH;
// FIXME - default should be json soon
protected String format = "xml";
protected String apiPath = "/api.php?";
// the client and it's cookies
private Client client;
private ArrayList<Object> cookies;
// mediaWikiVersion and site info
protected String userid;
SiteInfo siteinfo;
// Json unmarshaller
private Gson gson;
/**
* enable debugging
*
* @param debug
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
@Override
public boolean isDebug() {
return this.debug;
}
/**
* @return the siteurl
*/
public String getSiteurl() {
return siteurl;
}
/**
* @param siteurl
* the siteurl to set
*/
public void setSiteurl(String siteurl) {
this.siteurl = siteurl;
}
/**
* @return the scriptPath
*/
public String getScriptPath() {
return scriptPath;
}
/**
* @param scriptPath
* the scriptPath to set
*/
public void setScriptPath(String scriptPath) {
this.scriptPath = scriptPath;
}
/**
* construct me with no siteurl set
*
* @throws Exception
*/
public Mediawiki() throws Exception {
this(null);
}
/**
* construct a Mediawiki for the given url using the default Script path
*
* @param siteurl
* - the url to use
* @throws Exception
*/
public Mediawiki(String siteurl) throws Exception {
this(siteurl, DEFAULT_SCRIPTPATH);
}
/**
* construct a Mediawiki for the given url and scriptpath
*
* @param siteurl
* - the url to use
* @param pScriptPath
* - the scriptpath to use
* @throws Exception
*/
public Mediawiki(String siteurl, String pScriptPath) throws Exception {
init(siteurl, pScriptPath);
}
/**
* overrideable e.g for SSL configuration
*
* @throws Exception
*/
@Override
public void init(String siteurl, String scriptpath) throws Exception {
ApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
config.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES,
true);
client = ApacheHttpClient.create(config);
client.setFollowRedirects(true);
// org.apache.log4j.Logger.getLogger("httpclient").setLevel(Level.ERROR);
this.siteurl = siteurl;
this.scriptPath = scriptpath;
}
/**
* get a current IsoTimeStamp
*
* @return - the current timestamp
*/
public String getIsoTimeStamp() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
/**
* get a String from a given URL
*
* @param urlString
* @return
*/
public static String getStringFromUrl(String urlString) {
ApacheHttpClient lclient = ApacheHttpClient.create();
WebResource webResource = lclient.resource(urlString);
ClientResponse response = webResource.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("HTTP error code : " + response.getStatus());
}
String result = response.getEntity(String.class);
return result;
}
/**
* get the given Builder for the given queryUrl this is a wrapper to be able
* to debug all QueryUrl
*
* @param queryUrl
* - either a relative or absolute path
* @return
* @throws Exception
*/
public Builder getResource(String queryUrl) throws Exception {
if (debug)
LOGGER.log(Level.INFO, queryUrl);
WebResource wrs = client.resource(queryUrl);
Builder result = wrs.header("USER-AGENT", USER_AGENT);
return result;
}
/**
* get a Post response
*
* @param queryUrl
* @param params
* - direct query parameters
* @param token
* - a token if any
* @param pFormData
* - the form data - either as multipart of urlencoded
* @return - the client Response
* @throws Exception
*/
public ClientResponse getPostResponse(String queryUrl, String params,
TokenResult token, Object pFormDataObject) throws Exception {
params = params.replace("|", "%7C");
// modal handling of post
FormDataMultiPart form = null;
MultivaluedMap<String, String> lFormData = null;
if (pFormDataObject instanceof FormDataMultiPart) {
form = (FormDataMultiPart) pFormDataObject;
} else {
@SuppressWarnings("unchecked")
Map<String, String> pFormData = (Map<String, String>) pFormDataObject;
lFormData = new MultivaluedMapImpl();
if (pFormData != null) {
for (String key : pFormData.keySet()) {
lFormData.add(key, pFormData.get(key));
}
}
}
if (token != null) {
switch (token.tokenMode) {
case token1_24:
if (lFormData != null) {
lFormData.add(token.tokenName, token.token);
} else {
form.field(token.tokenName, token.token);
}
break;
default:
params += token.asParam();
}
}
Builder resource = getResource(queryUrl + params);
// FIXME allow to specify content type (not needed for Mediawiki itself
// but
// could be good for interfacing )
ClientResponse response = null;
if (lFormData != null) {
response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, lFormData);
} else {
response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, form);
}
return response;
}
public enum Method {
Post, Get, Head, Put
};
/**
* get a response for the given url and method
*
* @param url
* @param method
* @return
* @throws Exception
*/
public ClientResponse getResponse(String url, Method method)
throws Exception {
Builder resource = getResource(url);
ClientResponse response = null;
switch (method) {
case Get:
response = resource.get(ClientResponse.class);
break;
case Post:
response = resource.post(ClientResponse.class);
break;
case Head:
response = resource.head();
break;
case Put:
response = resource.put(ClientResponse.class);
break;
}
return response;
}
/**
* get the Response string
*
* @param response
* @return the String representation of a response
* @throws Exception
*/
public String getResponseString(ClientResponse response) throws Exception {
if (debug)
LOGGER.log(Level.INFO, "status: " + response.getStatus());
String responseText = response.getEntity(String.class);
if (response.getStatus() != 200) {
handleError("status " + response.getStatus() + ":'" + responseText + "'");
}
return responseText;
}
/**
* get a Map of parameter from a & delimited parameter list
*
* @param params
* - the list of parameters
* @return the map FIXME - should check that split creates and even number of
* entries - add test case for this
*/
public Map<String, String> getParamMap(String params) {
Map<String, String> result = new HashMap<String, String>();
String[] paramlist = params.split("&");
for (int i = 0; i < paramlist.length; i++) {
String[] parts = paramlist[i].split("=");
if (parts.length == 2)
result.put(parts[0], parts[1]);
}
return result;
}
/**
* get the action result for the given parameters
*
* @param action
* @param params
* @param token
* @param pFormData
* @param format
* - json or xml
* @return the String e.g. xml or json
* @throws Exception
*/
public String getActionResultText(String action, String params, TokenResult token,
Object pFormData, String format) throws Exception {
String queryUrl = siteurl + scriptPath + apiPath + "&action=" + action
+ "&format=" + format;
ClientResponse response;
// decide for the method to use for api access
response = this.getPostResponse(queryUrl, params, token, pFormData);
String text = this.getResponseString(response);
return text;
}
/**
* get the result for the given action and params
*
* @param action
* @param params
* @param token
* (may be null)
* @param formData
* (may be null)
* @format - the format to use e.g. json or xml
* @return the API result for the action
* @throws Exception
*/
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData, String format) throws Exception {
String text = this.getActionResultText(action, params, token, pFormData,
format);
Api api = null;
if ("xml".equals(format)) {
if (debug) {
// convert the xml to a more readable format
String xmlDebug = text.replace(">", ">\n");
LOGGER.log(Level.INFO, xmlDebug);
}
api = fromXML(text);
} else if ("json".equals(format)) {
if (gson==null)
gson=new Gson();
api=gson.fromJson(text, Api.class);
} else {
throw new IllegalStateException("unknown format " + format);
}
return api;
}
/**
* get the action result for the default format
* @param action
* @param params
* @param token
* @param pFormData
* @return - the action result
* @throws Exception
*/
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData) throws Exception {
return getActionResult(action, params, token, pFormData, format);
}
/**
* get the result for the given action and query
*
* @param action
* @param params
* @return the API result for the action
* @throws Exception
*/
public Api getActionResult(String action, String params) throws Exception {
Api result = this.getActionResult(action, params, null, null);
return result;
}
/**
* get the Result for the given query
*
* @param query
* @return the API result for the query
* @throws Exception
*/
public Api getQueryResult(String query) throws Exception {
Api result = this.getActionResult("query", query, null, null);
return result;
}
/**
* get a normalized | delimited (encoded as %7C) string of titles
*
* @param examplePages
* - the list of pages to get the titles for
* @return a string with all the titles e.g. Main%20Page%7CSome%20Page
* @throws Exception
*/
public String getTitles(List<String> titleList) throws Exception {
String titles = "";
String delim = "";
for (String title : titleList) {
titles = titles + delim + normalizeTitle(title);
delim = "%7C";
}
return titles;
}
/**
* get the siteinfo
*
* @return the siteinfo
* @throws Exception
*/
public SiteInfo getSiteInfo() throws Exception {
if (siteinfo == null) {
Api api = getQueryResult("&meta=siteinfo&siprop=general%7Cnamespaces");
Query query = api.getQuery();
setUpSiteInfo(query);
}
return siteinfo;
}
/**
* setup siteinfo for a query (e.g. for testing)
*
* @param query
*/
public void setUpSiteInfo(Query query) {
General general = query.getGeneral();
siteinfo = new SiteInfoImpl(general, query.getNamespaces());
}
/**
* check whether this is MediaWiki 1.28 or higher but make sure getVersion
* calls with readapidenied are ignored see
* https://github.com/WolfgangFahl/Mediawiki-Japi/issues/32
*
* @return
*/
public boolean isVersion128() {
String mwversion = "Mediawiki 1.27 or before";
try {
mwversion = this.getVersion();
} catch (Exception e) {
LOGGER.log(Level.INFO,
"Could not retrieve Mediawiki Version via API - will assume "
+ mwversion
+ " you might want to set the Version actively if you are on 1.28 and have the api blocked for non-logged in users");
}
boolean result = mwversion.compareToIgnoreCase("Mediawiki 1.28") >= 0;
return result;
}
/**
* prepare the login by getting the login token
*
* @param username
* @return the ApiResult
* @throws Exception
*/
public TokenResult prepareLogin(String username) throws Exception {
username = encode(username);
Api apiResult = null;
TokenResult token = new TokenResult();
token.tokenName = "lgtoken";
token.tokenMode = TokenMode.token1_19;
// see https://github.com/WolfgangFahl/Mediawiki-Japi/issues/31
if (this.isVersion128()) {
apiResult = this.getQueryResult("&meta=tokens&type=login");
super.handleError(apiResult);
token.token = apiResult.getQuery().getTokens().getLogintoken();
} else {
apiResult = getActionResult("login", "&lgname=" + username, null, null);
super.handleError(apiResult);
Login login = apiResult.getLogin();
token.token = login.getToken();
}
return token;
}
/**
* second step of login process
*
* @param token
* @param username
* @param password
* @return
* @throws Exception
*/
public Login login(TokenResult token, String username, String password)
throws Exception {
return login(token, username, password, null);
}
/**
* second step of login process
*
* @param token
* @param username
* @param password
* @param domain
* @return
* @throws Exception
*/
public Login login(TokenResult token, String username, String password,
String domain) throws Exception {
username = encode(username);
if (domain != null) {
domain = encode(domain);
}
Api apiResult = null;
// depends on MediaWiki version see
// https://test2.wikipedia.org/w/api.php?action=help&modules=clientlogin
if (this.isVersion128()) {
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("lgpassword", password);
lFormData.put("lgtoken", token.token);
if (domain != null) {
apiResult = getActionResult("login",
"&lgdomain=" + domain + "&lgname=" + username, null, lFormData);
} else {
apiResult = getActionResult("login", "&lgname=" + username, null,
lFormData);
}
// apiResult = getActionResult("clientlogin", "&lgname=" +
// username+"&loginreturnurl="+this.siteurl, null, lFormData);
} else {
password = encode(password);
if (domain != null) {
apiResult = getActionResult("login", "&lgdomain=" + domain + "&lgname="
+ username + "&lgpassword=" + password, token, null);
} else {
apiResult = getActionResult("login",
"&lgname=" + username + "&lgpassword=" + password, token, null);
}
}
Login login = apiResult.getLogin();
userid = login.getLguserid();
return login;
}
/**
* login with the given username, password and domain
*
* @param username
* @param password
* @param domain
* @return Login
* @throws Exception
*/
public Login login(String username, String password, String domain)
throws Exception {
// login is a two step process
// first we get a token
TokenResult token = prepareLogin(username);
// and then with the token we login using the password
Login login = login(token, username, password, domain);
return login;
}
/**
* login with the given username and password
*
* @param username
* @param password
* @return Login
* @throws Exception
*/
public Login login(String username, String password) throws Exception {
return login(username, password, null);
}
@Override
public boolean isLoggedIn() {
boolean result = userid != null;
return result;
}
/**
* end the session
*
* @throws Exception
*/
public void logout() throws Exception {
Api apiResult = getActionResult("logout", "", null, null);
if (apiResult != null) {
userid = null;
// FIXME check apiResult
}
if (cookies != null) {
cookies.clear();
cookies = null;
}
}
/**
* get the page Content for the given page Title
*
* @param pageTitle
* @param queryParams
* - extra query params e.g. for sections
* @param checkNotNull
* - check if the content should not be null
* @return the page Content
* @throws Exception
*/
public String getPageContent(String pageTitle, String queryParams,
boolean checkNotNull) throws Exception {
Api api = getQueryResult("&prop=revisions&rvprop=content" + queryParams
+ "&titles=" + normalizeTitle(pageTitle));
handleError(api);
List<Page> pages = api.getQuery().getPages();
String content = null;
if (pages != null) {
Page page = pages.get(0);
if (page != null) {
if (page.getRevisions().size() > 0) {
content = page.getRevisions().get(0).getValue();
}
}
}
if (checkNotNull && content == null) {
String errMsg = "pageTitle '" + pageTitle + "' not found";
this.handleError(errMsg);
}
return content;
}
/**
* get the page Content for the given page Title
*
* @param pageTitle
* @return the page Content
* @throws Exception
*/
public String getPageContent(String pageTitle) throws Exception {
String result = this.getPageContent(pageTitle, "", false);
return result;
}
/**
* get the text for the given section
*
* @param pageTitle
* @param sectionNumber
* @return
* @throws Exception
*/
public String getSectionText(String pageTitle, int sectionNumber)
throws Exception {
String result = this.getPageContent(pageTitle,
"&rvsection=" + sectionNumber, false);
return result;
}
@Override
public List<S> getSections(String pageTitle) throws Exception {
String params = "&prop=sections&page=" + pageTitle;
Parse parse = getParse(params);
List<S> sections = parse.getSections();
return sections;
}
@Override
public String getPageHtml(String pageTitle) throws Exception {
String params = "&page=" + encode(pageTitle);
Parse parse = getParse(params);
String html = parse.getText();
return html;
}
/**
* get the parse Result for the given params
*
* @param params
* @return the Parse Result
* @throws Exception
*/
public Parse getParse(String params) throws Exception {
String action = "parse";
Api api = getActionResult(action, params);
super.handleError(api);
return api.getParse();
}
/**
* get a list of pages for the given titles see
* <a href='http://www.mediawiki.org/wiki/API:Query'>API:Query</a>
*
* @param titleList
* @param rvprop
* - the revision properties
* @return the list of pages retrieved
* @throws Exception
*
* FIXME should be part of the Java Interface
*/
public List<Page> getPages(List<String> titleList, String rvprop)
throws Exception {
String titles = this.getTitles(titleList);
// https://www.mediawiki.org/wiki/API:Revisions#Parameters
Api api = getQueryResult(
"&titles=" + titles + "&prop=revisions&rvprop=" + rvprop);
handleError(api);
Query query = api.getQuery();
if (query == null) {
throw new Exception("query is null for getPages '" + titleList
+ "' rvprop='" + rvprop + "'");
}
List<Page> pages = query.getPages();
return pages;
}
/**
* get a list of pages for the given titles see
* <a href='http://www.mediawiki.org/wiki/API:Query'>API:Query</a>
*
* @param titleList
* @return
* @throws Exception
*/
public List<Page> getPages(List<String> titleList) throws Exception {
String rvprop = "content|ids|timestamp";
List<Page> result = this.getPages(titleList, rvprop);
return result;
}
/**
* the different modes of handling tokens - depending on MediaWiki version
*/
enum TokenMode {
token1_19, token1_20_23, token1_24
}
/**
* helper class to handle the different token modes
*
* @author wf
*
*/
class TokenResult {
String tokenName;
String token;
TokenMode tokenMode;
/**
* set my token - remove trailing backslash or +\ if necessary
*
* @param pToken
* - the token to set
*/
public void setToken(String pToken) {
token = pToken;
}
/**
* get me as a param string e.g. &lgtoken=1234 make sure the trailing \ or
* +\ are handled correctly see
* <a href= 'https://www.mediawiki.org/wiki/Manual:Edit_token'>Manual:
* Edit_token</a>
*
* @return - the resulting string
* @throws Exception
*/
public String asParam() throws Exception {
String lToken = token;
/*
* switch (tokenMode) { case token1_24: lToken=lToken.replace("+","");
* lToken=lToken.replace("\\",""); break; default:
*
* }
*/
// token=pToken+"%2B%5C";
// http://wikimedia.7.x6.nabble.com/Error-badtoken-Info-Invalid-token-td4977853.html
String result = "&" + tokenName + "=" + encode(lToken);
if (debug)
LOGGER.log(Level.INFO, "token " + token + "=>" + result);
return result;
}
}
/**
* get an edit token for the given page Title see
* <a href='https://www.mediawiki.org/wiki/API:Tokens'>API:Tokens</a>
*
* @param pageTitle
* @param type
* e.g. edit or delete
* @return the edit token for the page title
* @throws Exception
*/
public TokenResult getEditToken(String pageTitle, String type)
throws Exception {
pageTitle = normalizeTitle(pageTitle);
String editversion = "";
String action = "query";
String params = "&meta=tokens";
TokenMode tokenMode;
if (getVersion().compareToIgnoreCase("Mediawiki 1.24") >= 0) {
editversion = "Versions 1.24 and later";
tokenMode = TokenMode.token1_24;
params = "&meta=tokens";
} else if (getVersion().compareToIgnoreCase("Mediawiki 1.20") >= 0) {
editversion = "Versions 1.20-1.23";
tokenMode = TokenMode.token1_20_23;
action = "tokens";
params = "&type=" + type;
} else {
editversion = "Version 1.19 and earlier";
tokenMode = TokenMode.token1_19;
params = "&prop=info&7Crevisions&intoken=" + type + "&titles="
+ pageTitle;
}
if (debug) {
LOGGER.log(Level.INFO,
"handling " + type + " token for wiki version " + getVersion()
+ " as " + editversion + " with action=" + action + params);
}
Api api = getActionResult(action, params);
handleError(api);
TokenResult token = new TokenResult();
token.tokenMode = tokenMode;
token.tokenName = "token";
switch (tokenMode) {
case token1_19:
Page page = api.getQuery().getPages().get(0);
if (type.equals("edit")) {
token.setToken(page.getEdittoken());
} else if (type.equals("delete")) {
token.setToken(page.getDeletetoken());
}
break;
case token1_20_23:
if (type.equals("edit")) {
token.setToken(api.getTokens().getEdittoken());
} else if (type.equals("delete")) {
token.setToken(api.getTokens().getDeletetoken());
}
break;
default:
token.setToken(api.getQuery().getTokens().getCsrftoken());
break;
}
return token;
}
/**
* https://www.mediawiki.org/wiki/API:Edit
*/
@Override
public Edit edit(String pageTitle, String text, String summary)
throws Exception {
Edit result = this.edit(pageTitle, text, summary, true, false, -2, null,
null);
return result;
}
/**
* https://www.mediawiki.org/wiki/API:Delete/de
*
* @return info
*/
@Override
public Delete delete(String pageTitle, String reason) throws Exception {
Delete result = new Delete();
String pageContent = getPageContent(pageTitle);
if (pageContent != null && pageContent.contains(protectionMarker)) {
LOGGER.log(Level.WARNING, "page " + pageTitle + " is protected!");
} else {
TokenResult token = getEditToken(pageTitle, "delete");
if (token.token == null) {
throw new IllegalStateException(
"could not get " + token.tokenMode.toString() + " delete token for "
+ pageTitle + " ");
}
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("title", pageTitle);
lFormData.put("reason", reason);
String params = "";
Api api = this.getActionResult("delete", params, token, lFormData);
handleError(api);
result = api.getDelete();
}
return result;
}
@Override
public Edit edit(String pageTitle, String text, String summary, boolean minor,
boolean bot, int sectionNumber, String sectionTitle, Calendar basetime)
throws Exception {
Edit result = new Edit();
String pageContent = getPageContent(pageTitle);
if (pageContent != null && pageContent.contains(protectionMarker)) {
LOGGER.log(Level.WARNING, "page " + pageTitle + " is protected!");
} else {
TokenResult token = getEditToken(pageTitle, "edit");
Map<String, String> lFormData = new HashMap<String, String>();
lFormData.put("text", text);
lFormData.put("title", pageTitle);
lFormData.put("summary", summary);
if (minor)
lFormData.put("minor", "1");
if (bot)
lFormData.put("bot", "1");
switch (sectionNumber) {
case -1:
lFormData.put("section", "new");
if (sectionTitle != null)
lFormData.put("sectiontitle", sectionTitle);
break;
case -2:
break;
default:
lFormData.put("section", "" + sectionNumber);
break;
}
String params = "";
Api api = this.getActionResult("edit", params, token, lFormData);
handleError(api);
result = api.getEdit();
}
return result;
}
/**
* https://www.mediawiki.org/wiki/API:Upload
*/
@Override
public synchronized void upload(File fileToUpload, String filename,
String contents, String comment) throws Exception {
this.upload(new FileInputStream(fileToUpload), filename, contents, comment);
}
/**
* upload from the given inputstream
*
* @param fileToUpload
* @param filename
* @param contents
* @param comment
* @throws Exception
*/
public synchronized void upload(InputStream fileToUpload, String filename,
String contents, String comment) throws Exception {
TokenResult token = getEditToken("File:" + filename, "edit");
final FormDataMultiPart multiPart = new FormDataMultiPart();
// http://stackoverflow.com/questions/5772225/trying-to-upload-a-file-to-a-jax-rs-jersey-server
multiPart.bodyPart(new StreamDataBodyPart("file", fileToUpload));
multiPart.field("filename", filename);
multiPart.field("ignorewarnings", "true");
multiPart.field("text", contents);
if (!comment.isEmpty())
multiPart.field("comment", comment);
String params = "";
Api api = this.getActionResult("upload", params, token, multiPart);
handleError(api);
}
@Override
public void upload(Ii ii, String fileName, String pageContent)
throws Exception {
String url = ii.getUrl();
InputStream imageInput = new URL(url).openStream();
String comment = ii.getComment();
this.upload(imageInput, fileName, pageContent, comment);
}
/**
* getAllPages
*
* @param apfrom
* - may be null or empty
* @param aplimit
* @return
* @throws Exception
*/
public List<P> getAllPages(String apfrom, int aplimit) throws Exception {
String query = "&list=allpages";
if (apfrom != null && !apfrom.trim().equals("")) {
query += "&apfrom=" + apfrom;
}
query += "&aplimit=" + aplimit;
Api api = getQueryResult(query);
List<P> pageRefList = api.getQuery().getAllpages();
return pageRefList;
}
@Override
public List<Img> getAllImagesByTimeStamp(String aistart, String aiend,
int ailimit) throws Exception {
String query = "&list=allimages&aisort=timestamp";
if (aistart != null && !aistart.trim().equals("")) {
query += "&aistart=" + aistart;
}
if (aiend != null && !aiend.trim().equals("")) {
query += "&aiend=" + aiend;
}
query += "&ailimit=" + ailimit;
Api api = getQueryResult(query);
handleError(api);
List<Img> result = api.getQuery().getAllImages();
return result;
}
@Override
public List<Bl> getBacklinks(String pageTitle, String params, int bllimit)
throws Exception {
String query = "&list=backlinks&bltitle=" + normalizeTitle(pageTitle);
query += "&bllimit=" + bllimit;
query += params;
Api api = getQueryResult(query);
handleError(api);
List<Bl> result = api.getQuery().getBacklinks();
return result;
}
@Override
public List<Iu> getImageUsage(String imageTitle, String params, int limit)
throws Exception {
String query = "&list=imageusage&iutitle=" + normalizeTitle(imageTitle);
query += "&iulimit=" + limit;
query += params;
Api api = getQueryResult(query);
handleError(api);
List<Iu> result = api.getQuery().getImageusage();
return result;
}
/**
* handle the given Throwable (in commandline mode)
*
* @param t
*/
public void handle(Throwable t) {
System.out.flush();
System.err.println(t.getClass().getSimpleName() + ":" + t.getMessage());
if (debug)
t.printStackTrace();
}
/**
* show the Version
*/
public static void showVersion() {
System.err.println("Mediawiki-Japi Version: " + VERSION);
System.err.println();
System.err
.println(" github: https://github.com/WolfgangFahl/Mediawiki-Japi");
System.err.println("");
}
/**
* show a usage
*/
public void usage(String msg) {
System.err.println(msg);
showVersion();
System.err.println(" usage: java com.bitplan.mediawiki.japi.Mediawiki");
parser.printUsage(System.err);
exitCode = 1;
}
/**
* show Help
*/
public void showHelp() {
String msg = "Help\n" + "Mediawiki-Japi version " + VERSION
+ " has no functional command line interface\n"
+ "Please visit http://mediawiki-japi.bitplan.com for usage instructions";
usage(msg);
}
private CmdLineParser parser;
static int exitCode;
/**
* set to true for debugging
*/
@Option(name = "-d", aliases = {
"--debug" }, usage = "debug\nadds debugging output")
protected boolean debug = false;
@Option(name = "-h", aliases = { "--help" }, usage = "help\nshow this usage")
boolean showHelp = false;
@Option(name = "-v", aliases = {
"--version" }, usage = "showVersion\nshow current version if this switch is used")
boolean showVersion = false;
/**
* main instance - this is the non-static version of main - it will run as a
* static main would but return it's exitCode to the static main the static
* main will then decide whether to do a System.exit(exitCode) or not.
*
* @param args
* - command line arguments
* @return - the exit Code to be used by the static main program
*/
protected int maininstance(String[] args) {
parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (debug)
showVersion();
if (this.showVersion) {
showVersion();
} else if (this.showHelp) {
showHelp();
} else {
// FIXME - do something
// implement actions
System.err.println(
"Commandline interface is not functional in " + VERSION + " yet");
exitCode = 1;
// exitCode = 0;
}
} catch (CmdLineException e) {
// handling of wrong arguments
usage(e.getMessage());
} catch (Exception e) {
handle(e);
exitCode = 1;
}
return exitCode;
}
/**
* entry point e.g. for java -jar called provides a command line interface
*
* @param args
*/
public static void main(String args[]) {
Mediawiki wiki;
try {
wiki = new Mediawiki();
int result = wiki.maininstance(args);
if (!testMode && result != 0)
System.exit(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* create the given user account
*
* @param name
* @param eMail
* @param realname
* @param mailpassword
* @param reason
* @param language
* @throws Exception
*/
public Api createAccount(String name, String eMail, String realname,
boolean mailpassword, String reason, String language) throws Exception {
String params = "&name=" + name;
params += "&email=" + eMail;
params += "&realname=" + realname;
params += "&mailpassword=" + mailpassword;
params += "&reason=" + reason;
params += "&token=";
Api api = getActionResult("createaccount", params);
handleError(api);
String token = api.getCreateaccount().getToken();
params += token;
api = getActionResult("createaccount", params);
return api;
}
@Override
public Ii getImageInfo(String pageTitle) throws Exception {
// example
// https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=imageinfo&format=xml&iiprop=timestamp|user|userid|comment|parsedcomment|canonicaltitle|url|size|dimensions|sha1|mime|thumbmime|mediatype|metadata|commonmetadata|extmetadata|archivename|bitdepth|uploadwarning&titles=File%3AAlbert%20Einstein%20Head.jpg
String props = "timestamp";
props += "%7Cuser%7Cuserid%7Ccomment%7Cparsedcomment%7Curl%7Csize%7Cdimensions";
props += "%7Csha1%7Cmime%7Cthumbmime%7Cmediatype%7Carchivename%7Cbitdepth";
Api api = getQueryResult("&prop=imageinfo&iiprop=" + props + "&titles="
+ normalizeTitle(pageTitle));
handleError(api);
Ii ii = null;
List<Page> pages = api.getQuery().getPages();
if (pages != null) {
Page page = pages.get(0);
if (page != null) {
Imageinfo imageinfo = page.getImageinfo();
if (imageinfo != null) {
ii = imageinfo.getIi();
} else {
String errMsg = "imageinfo for pageTitle '" + pageTitle
+ "' not found";
this.handleError(errMsg);
}
}
}
if (ii == null) {
String errMsg = "pageTitle '" + pageTitle + "' not found";
this.handleError(errMsg);
}
return ii;
}
@Override
public List<Im> getImagesOnPage(String pageTitle, int imLimit)
throws Exception {
String query = "&titles=" + normalizeTitle(pageTitle)
+ "&prop=images&imlimit=" + imLimit;
Api api = getQueryResult(query);
handleError(api);
List<Im> result = new ArrayList<Im>();
Query lquery = api.getQuery();
if (lquery != null) {
List<Page> pages = lquery.getPages();
if (pages.size() > 0) {
Page page = pages.get(0);
result = page.getImages();
}
}
return result;
}
@Override
public List<Ii> getImageInfosForPage(String pageTitle, int imLimit)
throws Exception {
List<Im> images = this.getImagesOnPage(pageTitle, imLimit);
List<Ii> result = new ArrayList<Ii>();
for (Im image : images) {
Ii imageinfo = this.getImageInfo(image.getTitle());
if (imageinfo.getCanonicaltitle() == null) {
imageinfo.setCanonicaltitle(image.getTitle());
}
result.add(imageinfo);
}
return result;
}
/**
* get the recent changes see https://www.mediawiki.org/wiki/API:RecentChanges
*
* @param rcstart
* The timestamp to start listing from (May not be more than
* $wgRCMaxAge into the past, which on Wikimedia wikis is 30 days[1])
* @param rcend
* @param rclimit
* @return - the list of recent changes
* @throws Exception
*/
public List<Rc> getRecentChanges(String rcstart, String rcend,
Integer rclimit) throws Exception {
String query = "&list=recentchanges&rcprop=title%7Ctimestamp%7Csha1%7Cids%7Csizes%7Cflags%7Cuser";
if (rclimit != null) {
query += "&rclimit=" + rclimit;
}
if (rcstart != null) {
query += "&rcstart=" + rcstart;
}
if (rcend != null) {
query += "&rcend=" + rcend;
}
Api api = getQueryResult(query);
handleError(api);
List<Rc> rcList = api.getQuery().getRecentchanges();
rcList = sortByTitleAndFilterDoubles(rcList);
return rcList;
}
/**
* sort the given List by title and filter double titles
*
* @param rcList
* @return
*/
public List<Rc> sortByTitleAndFilterDoubles(List<Rc> rcList) {
List<Rc> result = new ArrayList<Rc>();
List<Rc> sorted = new ArrayList<Rc>();
sorted.addAll(rcList);
Collections.sort(sorted, new Comparator<Rc>() {
@Override
public int compare(Rc lRc, Rc rRc) {
int result = lRc.getTitle().compareTo(rRc.getTitle());
if (result == 0) {
result = rRc.getTimestamp().compare(lRc.getTimestamp());
}
return result;
}
});
Rc previous = null;
for (Rc rc : sorted) {
if (previous == null || (!rc.getTitle().equals(previous.getTitle()))) {
result.add(rc);
}
previous = rc;
}
Collections.sort(result, new Comparator<Rc>() {
@Override
public int compare(Rc lRc, Rc rRc) {
int result = rRc.getTimestamp().compare(lRc.getTimestamp());
return result;
}
});
return result;
}
/**
* convert a data to a MediaWiki API timestamp
*
* @param date
* @return
*/
public String dateToMWTimeStamp(Date date) {
SimpleDateFormat mwTimeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String result = mwTimeStampFormat.format(date);
return result;
}
/**
* get the most recent changes
*
* @param days
* @param rcLimit
* @return
* @throws Exception
*/
public List<Rc> getMostRecentChanges(int days, int rcLimit) throws Exception {
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -days);
Date date30daysbefore = cal.getTime();
String rcstart = dateToMWTimeStamp(today);
String rcend = dateToMWTimeStamp(date30daysbefore);
List<Rc> rcList = this.getRecentChanges(rcstart, rcend, rcLimit);
List<Rc> result = this.sortByTitleAndFilterDoubles(rcList);
return result;
}
}
| adds error handling for invalid xml responses | src/main/java/com/bitplan/mediawiki/japi/Mediawiki.java | adds error handling for invalid xml responses | <ide><path>rc/main/java/com/bitplan/mediawiki/japi/Mediawiki.java
<ide> String xmlDebug = text.replace(">", ">\n");
<ide> LOGGER.log(Level.INFO, xmlDebug);
<ide> }
<del> api = fromXML(text);
<add> if (text.startsWith("<?xml version"))
<add> api = fromXML(text);
<add> else {
<add> LOGGER.log(Level.SEVERE, text);
<add> throw new Exception("invalid xml:"+text);
<add> }
<ide> } else if ("json".equals(format)) {
<ide> if (gson==null)
<ide> gson=new Gson(); |
|
Java | apache-2.0 | 58aac142d4f32d64aeda05834dc86115c2b3124a | 0 | apache/geronimo-devtools | /*
* 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.geronimo.st.ui.editors;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import org.apache.geronimo.st.ui.Activator;
import org.apache.geronimo.st.ui.internal.Trace;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jst.server.core.FacetUtil;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.eclipse.wst.server.core.IRuntime;
/**
* @version $Rev$ $Date$
*/
public class SharedDeploymentPlanEditor extends AbstractGeronimoDeploymentPlanEditor {
private static Map loaders = new HashMap();
private IGeronimoFormContentLoader currentLoader = null;
static {
loadExtensionPoints();
}
/*
* (non-Javadoc)
*
* @see org.apache.geronimo.st.ui.editors.AbstractGeronimoDeploymentPlanEditor#doAddPages()
*/
public void doAddPages() throws PartInitException {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.doAddPages");
if (getDeploymentPlan() != null && getLoader() != null) {
currentLoader.doAddPages(this);
}
addSourcePage();
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.doAddPages");
}
private static synchronized void loadExtensionPoints() {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.loadExtensionPoints");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IConfigurationElement[] cf = registry.getConfigurationElementsFor(Activator.PLUGIN_ID, "loader");
for (int i = 0; i < cf.length; i++) {
IConfigurationElement element = cf[i];
if ("loader".equals(element.getName())) {
try {
IGeronimoFormContentLoader loader = (IGeronimoFormContentLoader) element.createExecutableExtension("class");
String version = element.getAttribute("version");
loaders.put(version, loader);
} catch (CoreException e) {
Trace.tracePoint("CoreException", "SharedDeploymentPlanEditor.loadExtensionPoints");
e.printStackTrace();
}
}
}
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.loadExtensionPoints");
}
/*
* (non-Javadoc)
*
* @see org.apache.geronimo.st.ui.editors.AbstractGeronimoDeploymentPlanEditor#loadDeploymentPlan(org.eclipse.core.resources.IFile)
*/
public JAXBElement loadDeploymentPlan(IFile file) {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.loadDeploymentPlan", file);
JAXBElement jaxbElement = getLoader() != null ? currentLoader.loadDeploymentPlan(file) : null;
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.loadDeploymentPlan", jaxbElement);
return jaxbElement;
}
public void saveDeploymentPlan(IFile file) throws IOException, JAXBException {
if (getLoader() != null) {
getLoader().saveDeploymentPlan(deploymentPlan, file);
}
}
private IGeronimoFormContentLoader getLoader() {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.getLoader");
if (currentLoader == null) {
IEditorInput input = getEditorInput();
if (input instanceof IFileEditorInput) {
IProject project = ((IFileEditorInput) input).getFile().getProject();
try {
IFacetedProject fp = ProjectFacetsManager.create(project);
if (fp == null) return null;
IRuntime runtime = FacetUtil.getRuntime(fp.getPrimaryRuntime());
if (runtime == null) return null;
String version = runtime.getRuntimeType().getVersion();
currentLoader = (IGeronimoFormContentLoader) loaders.get(version);
} catch (CoreException e) {
Trace.tracePoint("CoreException", "SharedDeploymentPlanEditor.getLoader");
e.printStackTrace();
} catch (IllegalArgumentException ie) {
Trace.tracePoint("IllegalArgumentException", "SharedDeploymentPlanEditor.getLoader");
throw new IllegalArgumentException("The project [" + project.getName() + "] does not have a Targeted Runtime specified.");
}
}
}
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.getLoader", currentLoader);
return currentLoader;
}
}
| plugins/org.apache.geronimo.st.ui/src/main/java/org/apache/geronimo/st/ui/editors/SharedDeploymentPlanEditor.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.geronimo.st.ui.editors;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import org.apache.geronimo.st.ui.Activator;
import org.apache.geronimo.st.ui.internal.Trace;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jst.server.core.FacetUtil;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.eclipse.wst.server.core.IRuntime;
/**
* @version $Rev$ $Date$
*/
public class SharedDeploymentPlanEditor extends AbstractGeronimoDeploymentPlanEditor {
private static Map loaders = new HashMap();
private IGeronimoFormContentLoader currentLoader = null;
static {
loadExtensionPoints();
}
/*
* (non-Javadoc)
*
* @see org.apache.geronimo.st.ui.editors.AbstractGeronimoDeploymentPlanEditor#doAddPages()
*/
public void doAddPages() throws PartInitException {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.doAddPages");
if (getDeploymentPlan() != null && getLoader() != null) {
currentLoader.doAddPages(this);
}
addSourcePage();
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.doAddPages");
}
private static synchronized void loadExtensionPoints() {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.loadExtensionPoints");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IConfigurationElement[] cf = registry.getConfigurationElementsFor(Activator.PLUGIN_ID, "loader");
for (int i = 0; i < cf.length; i++) {
IConfigurationElement element = cf[i];
if ("loader".equals(element.getName())) {
try {
IGeronimoFormContentLoader loader = (IGeronimoFormContentLoader) element.createExecutableExtension("class");
String version = element.getAttribute("version");
loaders.put(version, loader);
} catch (CoreException e) {
Trace.tracePoint("CoreException", "SharedDeploymentPlanEditor.loadExtensionPoints");
e.printStackTrace();
}
}
}
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.loadExtensionPoints");
}
/*
* (non-Javadoc)
*
* @see org.apache.geronimo.st.ui.editors.AbstractGeronimoDeploymentPlanEditor#loadDeploymentPlan(org.eclipse.core.resources.IFile)
*/
public JAXBElement loadDeploymentPlan(IFile file) {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.loadDeploymentPlan", file);
JAXBElement jaxbElement = getLoader() != null ? currentLoader.loadDeploymentPlan(file) : null;
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.loadDeploymentPlan", jaxbElement);
return jaxbElement;
}
public void saveDeploymentPlan(IFile file) throws IOException, JAXBException {
if (getLoader() != null) {
getLoader().saveDeploymentPlan(deploymentPlan, file);
}
}
private IGeronimoFormContentLoader getLoader() {
Trace.tracePoint("ENTRY", "SharedDeploymentPlanEditor.getLoader");
if (currentLoader == null) {
IEditorInput input = getEditorInput();
if (input instanceof IFileEditorInput) {
IProject project = ((IFileEditorInput) input).getFile().getProject();
try {
IFacetedProject fp = ProjectFacetsManager.create(project);
IRuntime runtime = FacetUtil.getRuntime(fp.getPrimaryRuntime());
String version = runtime.getRuntimeType().getVersion();
currentLoader = (IGeronimoFormContentLoader) loaders.get(version);
} catch (CoreException e) {
Trace.tracePoint("CoreException", "SharedDeploymentPlanEditor.getLoader");
e.printStackTrace();
} catch (IllegalArgumentException ie) {
Trace.tracePoint("IllegalArgumentException", "SharedDeploymentPlanEditor.getLoader");
throw new IllegalArgumentException("The project [" + project.getName() + "] does not have a Targeted Runtime specified.");
}
}
}
Trace.tracePoint("EXIT", "SharedDeploymentPlanEditor.getLoader", currentLoader);
return currentLoader;
}
}
| GERONIMODEVTOOLS-565 NullPointerException on opening openejb-jar.xml
git-svn-id: 7b63602214189898ed4bdcfe832e41633e363f7d@810840 13f79535-47bb-0310-9956-ffa450edef68
| plugins/org.apache.geronimo.st.ui/src/main/java/org/apache/geronimo/st/ui/editors/SharedDeploymentPlanEditor.java | GERONIMODEVTOOLS-565 NullPointerException on opening openejb-jar.xml | <ide><path>lugins/org.apache.geronimo.st.ui/src/main/java/org/apache/geronimo/st/ui/editors/SharedDeploymentPlanEditor.java
<ide> IProject project = ((IFileEditorInput) input).getFile().getProject();
<ide> try {
<ide> IFacetedProject fp = ProjectFacetsManager.create(project);
<add> if (fp == null) return null;
<ide> IRuntime runtime = FacetUtil.getRuntime(fp.getPrimaryRuntime());
<add> if (runtime == null) return null;
<ide> String version = runtime.getRuntimeType().getVersion();
<ide> currentLoader = (IGeronimoFormContentLoader) loaders.get(version);
<ide> } catch (CoreException e) { |
|
Java | apache-2.0 | e4428b03c8ea77e8beca3a3a90823a67ce1f1a89 | 0 | brother-eshop/dubbox,RoyZeng/dubbo,izerui/dubbo,dangdangdotcom/dubbox,lxq1008/dubbo,lxq1008/dubbo,grayaaa/dubbo,MX2015/dubbo,TonyLeee/dubbo,TonyLeee/dubbo,fzbook/dubboEvent,dangdangdotcom/dubbox,AllenRay/dubbo-ex,rogerchina/dubbo,MX2015/dubbo,cailin186/dubbox,maczam/dubbox,rabbitcount/dubbo,sunxiang0918/dubbo,wthuan/dubbox,manlonglin/dubbo,fultonlee1/dubbox,Karanyxy/IRepository,hermanzzp/dubbo,zzycjcg/dubbo,jieke-tao/dubbo,asherhu/dubbox,ligzy/dubbo,wangjingfei/dubbo,shuvigoss/dubbox,codingboys/dubbox,taohaolong/dubbo,rogerchina/dubbo,xianjunkuang/dubbos,codingboys/dubbox,OopsOutOfMemory/dubbo,finch0219/dubbo,qtvbwfn/dubbo,BianWenlong/dubbo,nickeyfff/dubbox,andydreaming/dubbo,npccsb/dubbox,sunxiang0918/dubbo,Kevin2030/dubbo,kutala/dubbo,dadarom/dubbo,atreeyang/dubbo,springning/dubbo,lichenq/dubbo,fengshao0907/dubbox,yuankui/dubbo,yunemr/dubbox,luyulong/dubbox,dangdangdotcom/dubbox,brother-eshop/dubbox,gaoxianglong/dubbo,kevintvh/dubbo,bpzhang/dubbo,winndows/dubbo,lsw0742/dubbox,yihaijun/dubbox,huangkunyhx/dubbox,atreeyang/dubbo,atreeyang/dubbo,bpzhang/dubbo,welloncn/dubbo,yuyijq/dubbo,hermanzzp/dubbo,nickeyfff/dubbox,juqkai/dubbo,flamezyg/dubbo,mingbotang/dubbo,lsjiguang/dangdangdotcom,Fushicho/dubbo,whubbt/dubbo,ServerStarted/dubbo,RandyChen1985/dubbo-ext,clj198606061111/dubbox_spring4,i54334/dubbo,RiverWeng/dubbo,liuxinglanyue/dubbox,daniellitoc/dubbo-Research,gaoxianglong/dubbo,tangqian/dubbo,nichoding/dubbo,followyourheart/dubbo,zouyoujin/dubbo,ys305751572/dubbo,nickeyfff/dubbox,huangkunyhx/dubbox,orzroa/dubbo,lacrazyboy/dubbox,yujiasun/dubbo,zzycjcg/dubbo,gdweijin/dubbo,wei121363/dubbo,DR-YangLong/dubbox,tisson/dubbox,welloncn/dubbo,Jeromefromcn/dubbox,yiyezhangmu/dubbox,nichoding/dubbo,xiaozhou322/dubbo-master,suyimin/dubbox,hl198181/dubbo,coolworker/dubbo,zouyoujin/dubbo,ys305751572/dubbo,liuxb945/dubbo,qtvbwfn/dubbo,manlonglin/dubbo,damy/dubbo,Karanyxy/IRepository,cf9lovely/cf_rp,wangcan2014/dubbo,11wuqingchao/dubbo,RandyChen1985/dubbo-ext,cf9lovely/cf_rp,xiaoguiguixm/dubbo,jkchensc/dubbo,hiboycomehere/dubbo,pipi668/dubbox,ligzy/dubbo,liuxb945/dubbo,lrysir/dubbo,ledotcom/le-dubbo,fzbook/dubboEvent,aglne/dubbo,kutala/dubbo,jkchensc/dubbo,finch0219/dubbo,daniellitoc/dubbo-Research,forever342/dubbo,fly3q/dubbo,gyk001/dubbox,ryankong/dubbo,loafer/dubbox,kevintvh/dubbo,ryankong/dubbo,codingboyli/dubbo,hyace/dubbo,shuvigoss/dubbox,13366348079/Dubbo,yunemr/dubbox,microIBM/dubbo,yiyezhangmu/dubbox,wuwenyu19860817/dubbo,sinsinpub/dubbo,microIBM/dubbo,uubu/dubbox,chengdedeng/dubbox,Karanyxy/IRepository,taohaolong/dubbo,uubu/dubbox,quyixia/dubbox,xiaocat963/dubbo,lichenq/dubbo,hutea/dubbo,ykqabc/dubbo,yuankui/dubbo,hermanzzp/dubbo,BianWenlong/dubbo,cenqiongyu/dubbo,JackyMoto/dubbo,wz12406/dubbo,liuxinglanyue/dubbox,yujiasun/dubbo,clj198606061111/dubbox_spring4,gjhuai/dubbo,DavidAlphaFox/dubbo,codingboys/dubbox,redbeans2015/dubbox,youjava/dubbo,nichoding/dubbo,majinkai/dubbox,springning/dubbo,gjhuai/dubbo,wthuan/dubbox,micmiu/dubbo,yshaojie/dubbo,xiaocat963/dubbo,karlchan-cn/dubbo,grayaaa/dubbo,delavior/dubbo,uubu/dubbox,huangping40/dubbox,clj198606061111/dubbox_spring4,coolworker/dubbo,hdp-piplus/dubbox,kk17/dubbox,lxq1008/dubbo,rabbitcount/dubbo,aglne/dubbo,suyimin/dubbox,wangjingfei/dubbo,tisson/dubbox,mosoft521/dubbox,qtvbwfn/dubbo,lzwlzw/dubbo,Jeromefromcn/dubbox,gdweijin/dubbo,13366348079/Dubbo,wusuoyongxin/dubbox,gjhuai/dubbo,ServerStarted/dubbo,jieke-tao/dubbo,livvyguo/dubbo,fengyie007/dubbo,lrysir/dubbo,gigold/dubbo,quyixia/dubbox,daodaoliang/dubbo,kk17/dubbox,andydreaming/dubbo,magintursh/dubbo,wtmilk/dubbo,hdp-piplus/dubbox,lsw0742/dubbox,softliumin/dubbo,zk279444107/dubbo,walkongrass/dubbo,orika/dubbo,qtvbwfn/dubbo,izerui/dubbo,yangaiche/dubbo,gaoxianglong/dubbo,Fushicho/dubbo,xiaoguiguixm/dubbo,liyong7514/dubbo,lovepoem/dubbo,ledotcom/le-dubbo,lovepoem/dubbo,remoting/dubbox,gavinage/dubbox,Jeromefromcn/dubbox,npccsb/dubbox,wthuan/dubbox,gwisoft/dubbo,npccsb/dubbox,sinsinpub/dubbo,kyle-liu/dubbo2study,xiaojunbeyond/dubbox,jerk1991/dubbo,bpzhang/dubbo,wtmilk/dubbo,yujiasun/dubbo,winndows/dubbo,kkllwww007/dubbox,fly3q/dubbo,wangjingfei/dubbo,kyle-liu/dubbo2study,loafer/dubbox,remoting/dubbox,loafer/dubbox,chengdedeng/dubbox,jkchensc/dubbo,jerk1991/dubbo,ronaldo9grey/dubbo,allen-zkm/dubbo,OopsOutOfMemory/dubbo,alibaba/dubbo,RiverWeng/dubbo,model919/dubbo,surlymo/dubbo,tangqian/dubbo,redbeans2015/dubbox,allen-zkm/dubbo,wtmilk/dubbo,MetSystem/dubbo,HHzzhz/dubbo,lsjiguang/dangdangdotcom,codingboyli/dubbo,ligzy/dubbo,archlevel/dubbo,huangkunyhx/dubbox,redbeans2015/dubbox,MetSystem/dubbo,softliumin/dubbo,lrysir/dubbo,zk279444107/dubbo,liuxb945/dubbo,ledotcom/le-dubbo,orika/dubbo,youjava/dubbo,11wuqingchao/dubbo,HHzzhz/dubbo,DavidAlphaFox/dubbo,yuyijq/dubbo,microIBM/dubbo,lsw0742/dubbox,hiboycomehere/dubbo,forever342/dubbo,wusuoyongxin/dubbox,gavinage/dubbox,gyk001/dubbox,delavior/dubbo,ykqabc/dubbo,daodaoliang/dubbo,surlymo/dubbo,MetSystem/dubbo,archlevel/dubbo,open-source-explore/dubbo,shuvigoss/dubbox,followyourheart/dubbo,ronaldo9grey/dubbo,RoyZeng/dubbo,lichenq/dubbo,TonyLeee/dubbo,JeffreyWei/dubbox,cenqiongyu/dubbo,allen-zkm/dubbo,kyle-liu/dubbo2study,karlchan-cn/dubbo,micmiu/dubbo,lovepoem/dubbo,wuwenyu19860817/dubbo,lsjiguang/dangdangdotcom,izerui/dubbo,yangaiche/dubbo,xianjunkuang/dubbos,yshaojie/dubbo,DR-YangLong/dubbox,JackyMoto/dubbo,MX2015/dubbo,JackyMoto/dubbo,cailin186/dubbox,gwisoft/dubbo,xiaojunbeyond/dubbox,wz12406/dubbo,micmiu/dubbo,kkllwww007/dubbox,11wuqingchao/dubbo,pipi668/dubbox,yshaojie/dubbo,damy/dubbo,wangcan2014/dubbo,gkqzdxajh/dubbo,forever342/dubbo,Kevin2030/dubbo,ryankong/dubbo,wuwen5/dubbo,lacrazyboy/dubbox,leesir/dubbo,finch0219/dubbo,livvyguo/dubbo,winndows/dubbo,xiaocat963/dubbo,manlonglin/dubbo,wuwen5/dubbo,xiaoguiguixm/dubbo,wangsan/dubbo,wangsan/dubbo,karlchan-cn/dubbo,hyace/dubbo,wangcan2014/dubbo,yinheli/dubbo,cailin186/dubbox,kutala/dubbo,JeffreyWei/dubbox,remoting/dubbox,juqkai/dubbo,quyixia/dubbox,liyong7514/dubbo,delavior/dubbo,gwisoft/dubbo,yuankui/dubbo,alibaba/dubbo,gigold/dubbo,springning/dubbo,zzycjcg/dubbo,luyulong/dubbox,cf9lovely/cf_rp,lzwlzw/dubbo,AllenRay/dubbo-ex,taohaolong/dubbo,jieke-tao/dubbo,wuwen5/dubbo,Kevin2030/dubbo,jerk1991/dubbo,welloncn/dubbo,yunemr/dubbox,ServerStarted/dubbo,hutea/dubbo,kevintvh/dubbo,walkongrass/dubbo,grayaaa/dubbo,yihaijun/dubbox,rogerchina/dubbo,wz12406/dubbo,sunxiang0918/dubbo,gdweijin/dubbo,fengshao0907/dubbox,fly3q/dubbo,luyulong/dubbox,ykqabc/dubbo,xiaozhou322/dubbo-master,kkllwww007/dubbox,xiaojunbeyond/dubbox,suyimin/dubbox,guoxu0514/dubbo,AllenRay/dubbo-ex,youjava/dubbo,maczam/dubbox,dadarom/dubbo,gkqzdxajh/dubbo,JasonHZXie/dubbo,yangaiche/dubbo,dadarom/dubbo,hdp-piplus/dubbox,juqkai/dubbo,mingbotang/dubbo,wei121363/dubbo,livvyguo/dubbo,fengshao0907/dubbox,gavinage/dubbox,orzroa/dubbo,BianWenlong/dubbo,ronaldo9grey/dubbo,JeffreyWei/dubbox,gkqzdxajh/dubbo,fengyie007/dubbo,liyong7514/dubbo,xianjunkuang/dubbos,wusuoyongxin/dubbox,pipi668/dubbox,yiyezhangmu/dubbox,majinkai/dubbox,huangping40/dubbox,yinheli/dubbo,DR-YangLong/dubbox,damy/dubbo,flamezyg/dubbo,lacrazyboy/dubbox,aglne/dubbo,fzbook/dubboEvent,leesir/dubbo,orika/dubbo,brother-eshop/dubbox,gyk001/dubbox,gigold/dubbo,wuwenyu19860817/dubbo,tangqian/dubbo,open-source-explore/dubbo,wei121363/dubbo,model919/dubbo,yihaijun/dubbox,fultonlee1/dubbox,cenqiongyu/dubbo,RoyZeng/dubbo,surlymo/dubbo,asherhu/dubbox,andydreaming/dubbo,RiverWeng/dubbo,mosoft521/dubbox,flamezyg/dubbo,coolworker/dubbo,orzroa/dubbo,softliumin/dubbo,daniellitoc/dubbo-Research,whubbt/dubbo,followyourheart/dubbo,wangsan/dubbo,magintursh/dubbo,guoxu0514/dubbo,Fushicho/dubbo,i54334/dubbo,DavidAlphaFox/dubbo,liuxinglanyue/dubbox,lzwlzw/dubbo,hutea/dubbo,OopsOutOfMemory/dubbo,hyace/dubbo,mosoft521/dubbox,kk17/dubbox,JasonHZXie/dubbo,fengyie007/dubbo,guoxu0514/dubbo,zk279444107/dubbo,i54334/dubbo,RandyChen1985/dubbo-ext,ys305751572/dubbo,maczam/dubbox,codingboyli/dubbo,magintursh/dubbo,walkongrass/dubbo,chengdedeng/dubbox,majinkai/dubbox,xiaozhou322/dubbo-master,HHzzhz/dubbo,13366348079/Dubbo,open-source-explore/dubbo,tisson/dubbox,leesir/dubbo,hl198181/dubbo,whubbt/dubbo,hl198181/dubbo,mingbotang/dubbo,hiboycomehere/dubbo,rabbitcount/dubbo,daodaoliang/dubbo,yinheli/dubbo,asherhu/dubbox,model919/dubbo,huangping40/dubbox,archlevel/dubbo,fultonlee1/dubbox,sinsinpub/dubbo,zouyoujin/dubbo | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.common.utils;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.alibaba.dubbo.common.model.Person;
import com.alibaba.dubbo.common.model.SerializablePerson;
import com.alibaba.dubbo.common.model.person.BigPerson;
import com.alibaba.dubbo.common.model.person.FullAddress;
import com.alibaba.dubbo.common.model.person.PersonInfo;
import com.alibaba.dubbo.common.model.person.PersonStatus;
import com.alibaba.dubbo.common.model.person.Phone;
/**
* @author ding.lid
*/
public class PojoUtilsTest {
public void assertObject(Object data) {
assertObject(data, null);
}
public void assertObject(Object data, Type type) {
Object generalize = PojoUtils.generalize(data);
Object realize = PojoUtils.realize(generalize, data.getClass(), type);
assertEquals(data, realize);
}
public <T> void assertArrayObject(T[] data) {
Object generalize = PojoUtils.generalize(data);
@SuppressWarnings("unchecked")
T[] realize = (T[]) PojoUtils.realize(generalize, data.getClass());
assertArrayEquals(data, realize);
}
@Test
public void test_primitive() throws Exception {
assertObject(Boolean.TRUE);
assertObject(Boolean.FALSE);
assertObject(Byte.valueOf((byte) 78));
assertObject('a');
assertObject('中');
assertObject(Short.valueOf((short) 37));
assertObject(78);
assertObject(123456789L);
assertObject(3.14F);
assertObject(3.14D);
}
@Test
public void test_pojo() throws Exception {
assertObject(new Person());
assertObject(new SerializablePerson());
}
@Test
public void test_Map_List_pojo() throws Exception {
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
List<Object> list = new ArrayList<Object>();
list.add(new Person());
list.add(new SerializablePerson());
map.put("k", list);
Object generalize = PojoUtils.generalize(map);
Object realize = PojoUtils.realize(generalize, Map.class);
assertEquals(map, realize);
}
@Test
public void test_PrimitiveArray() throws Exception {
assertObject(new boolean[] { true, false });
assertObject(new Boolean[] { true, false, true });
assertObject(new byte[] { 1, 12, 28, 78 });
assertObject(new Byte[] { 1, 12, 28, 78 });
assertObject(new char[] { 'a', '中', '无' });
assertObject(new Character[] { 'a', '中', '无' });
assertObject(new short[] { 37, 39, 12 });
assertObject(new Short[] { 37, 39, 12 });
assertObject(new int[] { 37, -39, 12456 });
assertObject(new Integer[] { 37, -39, 12456 });
assertObject(new long[] { 37L, -39L, 123456789L });
assertObject(new Long[] { 37L, -39L, 123456789L });
assertObject(new float[] { 37F, -3.14F, 123456.7F });
assertObject(new Float[] { 37F, -39F, 123456.7F });
assertObject(new double[] { 37D, -3.14D, 123456.7D });
assertObject(new Double[] { 37D, -39D, 123456.7D});
assertArrayObject(new Boolean[] { true, false, true });
assertArrayObject(new Byte[] { 1, 12, 28, 78 });
assertArrayObject(new Character[] { 'a', '中', '无' });
assertArrayObject(new Short[] { 37, 39, 12 });
assertArrayObject(new Integer[] { 37, -39, 12456 });
assertArrayObject(new Long[] { 37L, -39L, 123456789L });
assertArrayObject(new Float[] { 37F, -39F, 123456.7F });
assertArrayObject(new Double[] { 37D, -39D, 123456.7D});
}
@Test
public void test_PojoArray() throws Exception {
Person[] array = new Person[2];
array[0] = new Person();
{
Person person = new Person();
person.setName("xxxx");
array[1] = person;
}
assertArrayObject(array);
}
public List<Person> returnListPersonMethod() {return null;}
public BigPerson returnBigPersonMethod() {return null;}
public Type getType(String methodName){
Method method;
try {
method = getClass().getDeclaredMethod(methodName, new Class<?>[]{} );
} catch (Exception e) {
throw new IllegalStateException(e);
}
Type gtype = method.getGenericReturnType();
return gtype;
}
@Test
public void test_simpleCollection() throws Exception {
Type gtype = getType("returnListPersonMethod");
List<Person> list = new ArrayList<Person>();
list.add(new Person());
{
Person person = new Person();
person.setName("xxxx");
list.add(person);
}
assertObject(list,gtype);
}
BigPerson bigPerson;
{
bigPerson = new BigPerson();
bigPerson.setPersonId("id1");
bigPerson.setLoginName("name1");
bigPerson.setStatus(PersonStatus.ENABLED);
bigPerson.setEmail("[email protected]");
bigPerson.setPenName("pname");
ArrayList<Phone> phones = new ArrayList<Phone>();
Phone phone1 = new Phone("86", "0571", "11223344", "001");
Phone phone2 = new Phone("86", "0571", "11223344", "002");
phones.add(phone1);
phones.add(phone2);
PersonInfo pi = new PersonInfo();
pi.setPhones(phones);
Phone fax = new Phone("86", "0571", "11223344", null);
pi.setFax(fax);
FullAddress addr = new FullAddress("CN", "zj", "1234", "Road1", "333444");
pi.setFullAddress(addr);
pi.setMobileNo("1122334455");
pi.setMale(true);
pi.setDepartment("b2b");
pi.setHomepageUrl("www.abc.com");
pi.setJobTitle("dev");
pi.setName("name2");
bigPerson.setInfoProfile(pi);
}
@Test
public void test_total() throws Exception {
Object generalize = PojoUtils.generalize(bigPerson);
Type gtype = getType("returnBigPersonMethod");
Object realize = PojoUtils.realize(generalize, BigPerson.class,gtype);
assertEquals(bigPerson, realize);
}
@Test
public void test_total_Array() throws Exception {
Object[] persons = new Object[] { bigPerson, bigPerson, bigPerson };
Object generalize = PojoUtils.generalize(persons);
Object[] realize = (Object[]) PojoUtils.realize(generalize, Object[].class);
assertArrayEquals(persons, realize);
}
// 循环测试
public static class Parent {
String name;
int age;
Child child;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
public static class Child {
String toy;
public String getToy() {
return toy;
}
public void setToy(String toy) {
this.toy = toy;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
Parent parent;
}
@Test
public void test_Loop_pojo() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Object generalize = PojoUtils.generalize(p);
Parent parent = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_Loop_Map() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", "v");
map.put("m", map);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> ret = (Map<String, Object>) PojoUtils.realize(generalize, Map.class);
assertEquals("v", ret.get("k"));
assertSame(ret, ret.get("m"));
}
@Test
public void test_LoopPojoInMap() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", p);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> realize = (Map<String, Object>) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType"));
Parent parent = (Parent) realize.get("k");
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_LoopPojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_PojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
}
public void setLong(long l){}
public void setInt(int l){}
public List<Parent> getListGenericType(){return null;};
public Map<String, Parent> getMapGenericType(){return null;};
// java.lang.IllegalArgumentException: argument type mismatch
@Test
public void test_realize_LongPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setLong", long.class);
assertNotNull(method);
Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
public void test_realize_IntPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setInt", int.class);
assertNotNull(method);
Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
} | dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.common.utils;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.alibaba.dubbo.common.model.Person;
import com.alibaba.dubbo.common.model.SerializablePerson;
import com.alibaba.dubbo.common.model.person.BigPerson;
import com.alibaba.dubbo.common.model.person.FullAddress;
import com.alibaba.dubbo.common.model.person.PersonInfo;
import com.alibaba.dubbo.common.model.person.PersonStatus;
import com.alibaba.dubbo.common.model.person.Phone;
/**
* @author ding.lid
*/
public class PojoUtilsTest {
public void assertObject(Object data) {
assertObject(data, null);
}
public void assertObject(Object data, Type type) {
Object generalize = PojoUtils.generalize(data);
Object realize = PojoUtils.realize(generalize, data.getClass(), type);
assertEquals(data, realize);
}
public <T> void assertArrayObject(T[] data) {
Object generalize = PojoUtils.generalize(data);
@SuppressWarnings("unchecked")
T[] realize = (T[]) PojoUtils.realize(generalize, data.getClass());
assertArrayEquals(data, realize);
}
@Test
public void test_primitive() throws Exception {
assertObject(Boolean.TRUE);
assertObject(Boolean.FALSE);
assertObject(Byte.valueOf((byte) 78));
assertObject('a');
assertObject('中');
assertObject(Short.valueOf((short) 37));
assertObject(78);
assertObject(123456789L);
assertObject(3.14F);
assertObject(3.14D);
}
@Test
public void test_pojo() throws Exception {
assertObject(new Person());
assertObject(new SerializablePerson());
}
@Test
public void test_Map_List_pojo() throws Exception {
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
List<Object> list = new ArrayList<Object>();
list.add(new Person());
list.add(new SerializablePerson());
map.put("k", list);
Object generalize = PojoUtils.generalize(map);
Object realize = PojoUtils.realize(generalize, Map.class);
assertEquals(map, realize);
}
@Test
public void test_PrimitiveArray() throws Exception {
assertObject(new boolean[] { true, false });
assertObject(new Boolean[] { true, false, true });
assertObject(new byte[] { 1, 12, 28, 78 });
assertObject(new Byte[] { 1, 12, 28, 78 });
assertObject(new char[] { 'a', '中', '无' });
assertObject(new Character[] { 'a', '中', '无' });
assertObject(new short[] { 37, 39, 12 });
assertObject(new Short[] { 37, 39, 12 });
assertObject(new int[] { 37, -39, 12456 });
assertObject(new Integer[] { 37, -39, 12456 });
assertObject(new long[] { 37L, -39L, 123456789L });
assertObject(new Long[] { 37L, -39L, 123456789L });
assertObject(new float[] { 37F, -3.14F, 123456.7F });
assertObject(new Float[] { 37F, -39F, 123456.7F });
assertObject(new double[] { 37D, -3.14D, 123456.7D });
assertObject(new Double[] { 37D, -39D, 123456.7D});
assertArrayObject(new Boolean[] { true, false, true });
assertArrayObject(new Byte[] { 1, 12, 28, 78 });
assertArrayObject(new Character[] { 'a', '中', '无' });
assertArrayObject(new Short[] { 37, 39, 12 });
assertArrayObject(new Integer[] { 37, -39, 12456 });
assertArrayObject(new Long[] { 37L, -39L, 123456789L });
assertArrayObject(new Float[] { 37F, -39F, 123456.7F });
assertArrayObject(new Double[] { 37D, -39D, 123456.7D});
}
@Test
public void test_PojoArray() throws Exception {
Person[] array = new Person[2];
array[0] = new Person();
{
Person person = new Person();
person.setName("xxxx");
array[1] = person;
}
assertArrayObject(array);
}
public List<Person> returnListPersonMethod() {return null;}
public BigPerson returnBigPersonMethod() {return null;}
public Type getType(String methodName){
Method method;
try {
method = getClass().getDeclaredMethod(methodName, new Class<?>[]{} );
} catch (Exception e) {
throw new IllegalStateException(e);
}
Type gtype = method.getGenericReturnType();
return gtype;
}
@Test
public void test_simpleCollection() throws Exception {
Type gtype = getType("returnListPersonMethod");
List<Person> list = new ArrayList<Person>();
list.add(new Person());
{
Person person = new Person();
person.setName("xxxx");
list.add(person);
}
assertObject(list,gtype);
}
BigPerson bigPerson;
{
bigPerson = new BigPerson();
bigPerson.setPersonId("id1");
bigPerson.setLoginName("name1");
bigPerson.setStatus(PersonStatus.ENABLED);
bigPerson.setEmail("[email protected]");
bigPerson.setPenName("pname");
ArrayList<Phone> phones = new ArrayList<Phone>();
Phone phone1 = new Phone("86", "0571", "11223344", "001");
Phone phone2 = new Phone("86", "0571", "11223344", "002");
phones.add(phone1);
phones.add(phone2);
PersonInfo pi = new PersonInfo();
pi.setPhones(phones);
Phone fax = new Phone("86", "0571", "11223344", null);
pi.setFax(fax);
FullAddress addr = new FullAddress("CN", "zj", "1234", "Road1", "333444");
pi.setFullAddress(addr);
pi.setMobileNo("1122334455");
pi.setMale(true);
pi.setDepartment("b2b");
pi.setHomepageUrl("www.abc.com");
pi.setJobTitle("dev");
pi.setName("name2");
bigPerson.setInfoProfile(pi);
}
@Test
public void test_total() throws Exception {
Object generalize = PojoUtils.generalize(bigPerson);
Type gtype = getType("returnBigPersonMethod");
Object realize = PojoUtils.realize(generalize, BigPerson.class,gtype);
assertEquals(bigPerson, realize);
}
@Test
public void test_total_Array() throws Exception {
Object[] persons = new Object[] { bigPerson, bigPerson, bigPerson };
Object generalize = PojoUtils.generalize(persons);
Object[] realize = (Object[]) PojoUtils.realize(generalize, Object[].class);
assertArrayEquals(persons, realize);
}
// 循环测试
public static class Parent {
String name;
int age;
Child child;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
public static class Child {
String toy;
public String getToy() {
return toy;
}
public void setToy(String toy) {
this.toy = toy;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
Parent parent;
}
@Test
public void test_Loop_pojo() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Object generalize = PojoUtils.generalize(p);
Parent parent = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_Loop_Map() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", "v");
map.put("m", map);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> ret = (Map<String, Object>) PojoUtils.realize(generalize, Map.class);
assertEquals("v", ret.get("k"));
assertSame(ret, ret.get("m"));
}
@Test
public void test_LoopPojoInMap() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", p);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> realize = (Map<String, Object>) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType"));
Parent parent = (Parent) realize.get("k");
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_LoopPojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
public void test_PojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
}
public void setLong(long l){}
public void setInt(int l){}
public List<Parent> getListGenericType(){return null;};
public Map<String, Parent> getMapGenericType(){return null;};
// java.lang.IllegalArgumentException: argument type mismatch
@Test
public void test_realize_LongPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setLong", long.class);
assertNotNull(method);
Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
public void test_realize_IntPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setInt", int.class);
assertNotNull(method);
Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
} | 修改错误的testcase
git-svn-id: 3d0e7b608a819e97e591a7b753bfd1a27aaeb5ee@1520 1a56cb94-b969-4eaa-88fa-be21384802f2
| dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java | 修改错误的testcase | <ide><path>ubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import com.alibaba.dubbo.common.model.Person; |
|
Java | mit | 419d837a7499b8c02cb8f46f02b40b9365f2bbec | 0 | Juancard/parallel-and-distributed-IR,Juancard/parallel-and-distributed-IR,Juancard/parallel-and-distributed-IR | package Model;
import java.io.DataInputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class Query{
private final static java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
private HashMap<Integer, Integer> termsFreq;
private IRNormalizer normalizer;
private HashMap<String, Integer> vocabulary;
public Query(HashMap<Integer, Integer> termsFreq){
this.termsFreq = termsFreq;
}
public Query(
String query,
HashMap<String, Integer> vocabulary,
IRNormalizer normalizer
){
this.vocabulary = vocabulary;
this.normalizer = normalizer;
this.termsFreq = new HashMap<Integer, Integer>();
String queryNormalized = this.normalizer.normalize(query);
this.setTermsAndWeights(this.normalizer.tokenize(queryNormalized));
}
private void setTermsAndWeights(String[] tokens){
boolean isTerm = false;
ArrayList<String> tokensDiscarded = new ArrayList<String>();
for (String token : tokens){
isTerm = this.normalizer.isValidTermSize(token)
&& !this.normalizer.isStopword(token)
&& this.vocabulary.containsKey(token);
if (isTerm)
this.addQueryTerm(token);
else
tokensDiscarded.add(token);
}
if (!tokensDiscarded.isEmpty())
LOGGER.info("Tokens discarded: " + tokensDiscarded);
}
private void addQueryTerm(String token){
int termId = this.vocabulary.get(token);
int weight = this.termsFreq.containsKey(termId) ? this.termsFreq.get(termId) : 0;
this.termsFreq.put(termId, weight + 1);
}
public boolean isEmptyOfTerms(){
return this.termsFreq.isEmpty();
}
public void socketRead(DataInputStream out) {}
public int getNumberOfTerms(){
return this.termsFreq.size();
}
@Override
public String toString() {
String qStr = "";
for (Integer termId : this.termsFreq.keySet()){
qStr += termId + ":" + this.termsFreq.get(termId) + ";";
}
return "Query{" +
qStr +
'}';
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Query)) {
return false;
}
Query q = (Query) o;
return this.termsFreq.equals(q.termsFreq);
}
//Idea from effective Java : Item 9
@Override
public int hashCode() {
int result = 17;
result = 31 * result + this.termsFreq.hashCode();
return result;
}
public HashMap<Integer, Integer> getTermsAndFrequency() {
return termsFreq;
}
}
| IR_server/java_src/Model/Query.java | package Model;
import java.io.DataInputStream;
import java.util.HashMap;
public class Query{
private HashMap<Integer, Integer> termsFreq;
private IRNormalizer normalizer;
private HashMap<String, Integer> vocabulary;
public Query(HashMap<Integer, Integer> termsFreq){
this.termsFreq = termsFreq;
}
public Query(
String query,
HashMap<String, Integer> vocabulary,
IRNormalizer normalizer
){
this.vocabulary = vocabulary;
this.normalizer = normalizer;
this.termsFreq = new HashMap<Integer, Integer>();
String queryNormalized = this.normalizer.normalize(query);
this.setTermsAndWeights(this.normalizer.tokenize(queryNormalized));
}
private void setTermsAndWeights(String[] tokens){
boolean isTerm = false;
for (String token : tokens){
isTerm = this.normalizer.isValidTermSize(token)
&& this.normalizer.isStopword(token)
&& this.vocabulary.containsKey(token);
if (isTerm)
this.addQueryTerm(token);
}
}
private void addQueryTerm(String token){
int termId = this.vocabulary.get(token);
int weight = this.termsFreq.containsKey(termId) ? this.termsFreq.get(termId) : 0;
this.termsFreq.put(termId, weight + 1);
}
public boolean isEmptyOfTerms(){
return this.termsFreq.isEmpty();
}
public void socketRead(DataInputStream out) {}
public int getNumberOfTerms(){
return this.termsFreq.size();
}
@Override
public String toString() {
String qStr = "";
for (Integer termId : this.termsFreq.keySet()){
qStr += termId + ":" + this.termsFreq.get(termId) + ";";
}
return "Query{" +
qStr +
'}';
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Query)) {
return false;
}
Query q = (Query) o;
return this.termsFreq.equals(q.termsFreq);
}
//Idea from effective Java : Item 9
@Override
public int hashCode() {
int result = 17;
result = 31 * result + this.termsFreq.hashCode();
return result;
}
public HashMap<Integer, Integer> getTermsAndFrequency() {
return termsFreq;
}
}
| ir server: on evaluation: show discarded tokens of query
| IR_server/java_src/Model/Query.java | ir server: on evaluation: show discarded tokens of query | <ide><path>R_server/java_src/Model/Query.java
<ide> package Model;
<ide>
<ide> import java.io.DataInputStream;
<add>import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide>
<ide> public class Query{
<add> private final static java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
<ide>
<ide> private HashMap<Integer, Integer> termsFreq;
<ide> private IRNormalizer normalizer;
<ide>
<ide> private void setTermsAndWeights(String[] tokens){
<ide> boolean isTerm = false;
<add> ArrayList<String> tokensDiscarded = new ArrayList<String>();
<ide> for (String token : tokens){
<ide> isTerm = this.normalizer.isValidTermSize(token)
<del> && this.normalizer.isStopword(token)
<add> && !this.normalizer.isStopword(token)
<ide> && this.vocabulary.containsKey(token);
<ide> if (isTerm)
<ide> this.addQueryTerm(token);
<add> else
<add> tokensDiscarded.add(token);
<ide> }
<add> if (!tokensDiscarded.isEmpty())
<add> LOGGER.info("Tokens discarded: " + tokensDiscarded);
<ide> }
<ide>
<ide> private void addQueryTerm(String token){ |
|
Java | apache-2.0 | 3c3d162159f75bf143e795db581154ea608ab0b6 | 0 | millmanorama/autopsy,rcordovano/autopsy,APriestman/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,millmanorama/autopsy,esaunders/autopsy,APriestman/autopsy,esaunders/autopsy,millmanorama/autopsy,rcordovano/autopsy,millmanorama/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,APriestman/autopsy,APriestman/autopsy | /*
* Central Repository
*
* Copyright 2015-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.centralrepository.contentviewer;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import java.util.stream.Collectors;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.DEFAULT_OPTION;
import static javax.swing.JOptionPane.PLAIN_MESSAGE;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.openide.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContentViewer;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttribute;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamArtifactUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationDataSource;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskException;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskData;
/**
* View correlation results from other cases
*/
@ServiceProvider(service = DataContentViewer.class, position = 8)
@Messages({"DataContentViewerOtherCases.title=Other Occurrences",
"DataContentViewerOtherCases.toolTip=Displays instances of the selected file/artifact from other occurrences.",})
public class DataContentViewerOtherCases extends javax.swing.JPanel implements DataContentViewer {
private final static Logger LOGGER = Logger.getLogger(DataContentViewerOtherCases.class.getName());
private final DataContentViewerOtherCasesTableModel tableModel;
private final Collection<CorrelationAttribute> correlationAttributes;
/**
* Could be null.
*/
private AbstractFile file;
/**
* Creates new form DataContentViewerOtherCases
*/
public DataContentViewerOtherCases() {
this.tableModel = new DataContentViewerOtherCasesTableModel();
this.correlationAttributes = new ArrayList<>();
initComponents();
customizeComponents();
reset();
}
private void customizeComponents() {
ActionListener actList = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem jmi = (JMenuItem) e.getSource();
if (jmi.equals(selectAllMenuItem)) {
otherCasesTable.selectAll();
} else if (jmi.equals(showCaseDetailsMenuItem)) {
showCaseDetails(otherCasesTable.getSelectedRow());
} else if (jmi.equals(exportToCSVMenuItem)) {
try {
saveToCSV();
} catch (NoCurrentCaseException ex) {
LOGGER.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
}
} else if (jmi.equals(showCommonalityMenuItem)) {
showCommonalityDetails();
}
}
};
exportToCSVMenuItem.addActionListener(actList);
selectAllMenuItem.addActionListener(actList);
showCaseDetailsMenuItem.addActionListener(actList);
showCommonalityMenuItem.addActionListener(actList);
// Set background of every nth row as light grey.
TableCellRenderer renderer = new DataContentViewerOtherCasesTableCellRenderer();
otherCasesTable.setDefaultRenderer(Object.class, renderer);
tableStatusPanelLabel.setVisible(false);
}
@Messages({"DataContentViewerOtherCases.correlatedArtifacts.isEmpty=There are no files or artifacts to correlate.",
"# {0} - commonality percentage",
"# {1} - correlation type",
"# {2} - correlation value",
"DataContentViewerOtherCases.correlatedArtifacts.byType={0}% of data sources have {2} (type: {1})\n",
"DataContentViewerOtherCases.correlatedArtifacts.title=Attribute Frequency",
"DataContentViewerOtherCases.correlatedArtifacts.failed=Failed to get frequency details."})
/**
* Show how common the selected
*/
private void showCommonalityDetails() {
if (correlationAttributes.isEmpty()) {
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
Bundle.DataContentViewerOtherCases_correlatedArtifacts_isEmpty(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, PLAIN_MESSAGE);
} else {
StringBuilder msg = new StringBuilder();
int percentage;
try {
EamDb dbManager = EamDb.getInstance();
for (CorrelationAttribute eamArtifact : correlationAttributes) {
percentage = dbManager.getFrequencyPercentage(eamArtifact);
msg.append(Bundle.DataContentViewerOtherCases_correlatedArtifacts_byType(percentage,
eamArtifact.getCorrelationType().getDisplayName(),
eamArtifact.getCorrelationValue()));
}
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
msg.toString(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, PLAIN_MESSAGE);
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error getting commonality details.", ex);
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
Bundle.DataContentViewerOtherCases_correlatedArtifacts_failed(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, ERROR_MESSAGE);
}
}
}
@Messages({"DataContentViewerOtherCases.caseDetailsDialog.notSelected=No Row Selected",
"DataContentViewerOtherCases.caseDetailsDialog.noDetails=No details for this case.",
"DataContentViewerOtherCases.caseDetailsDialog.noDetailsReference=No case details for Global reference properties.",
"DataContentViewerOtherCases.caseDetailsDialog.noCaseNameError=Error",
"DataContentViewerOtherCases.noOpenCase.errMsg=No open case available."})
private void showCaseDetails(int selectedRowViewIdx) {
Case openCase;
try {
openCase = Case.getOpenCase();
} catch (NoCurrentCaseException ex) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_noOpenCase_errMsg(),
Bundle.DataContentViewerOtherCases_noOpenCase_errMsg(),
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
String caseDisplayName = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noCaseNameError();
try {
if (-1 != selectedRowViewIdx) {
EamDb dbManager = EamDb.getInstance();
int selectedRowModelIdx = otherCasesTable.convertRowIndexToModel(selectedRowViewIdx);
CorrelationAttribute eamArtifact = (CorrelationAttribute) tableModel.getRow(selectedRowModelIdx);
CorrelationCase eamCasePartial = eamArtifact.getInstances().get(0).getCorrelationCase();
if (eamCasePartial == null) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetailsReference(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
caseDisplayName = eamCasePartial.getDisplayName();
// query case details
CorrelationCase eamCase = dbManager.getCase(openCase);
if (eamCase == null) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
// display case details
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
eamCase.getCaseDetailsOptionsPaneDialog(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
} else {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_notSelected(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
}
} catch (EamDbException ex) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
}
}
private void saveToCSV() throws NoCurrentCaseException {
if (0 != otherCasesTable.getSelectedRowCount()) {
Calendar now = Calendar.getInstance();
String fileName = String.format("%1$tY%1$tm%1$te%1$tI%1$tM%1$tS_other_data_sources.csv", now);
CSVFileChooser.setCurrentDirectory(new File(Case.getOpenCase().getExportDirectory()));
CSVFileChooser.setSelectedFile(new File(fileName));
CSVFileChooser.setFileFilter(new FileNameExtensionFilter("csv file", "csv"));
int returnVal = CSVFileChooser.showSaveDialog(otherCasesTable);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = CSVFileChooser.getSelectedFile();
if (!selectedFile.getName().endsWith(".csv")) { // NON-NLS
selectedFile = new File(selectedFile.toString() + ".csv"); // NON-NLS
}
writeSelectedRowsToFileAsCSV(selectedFile);
}
}
}
private void writeSelectedRowsToFileAsCSV(File destFile) {
StringBuilder content;
int[] selectedRowViewIndices = otherCasesTable.getSelectedRows();
int colCount = tableModel.getColumnCount();
try (BufferedWriter writer = Files.newBufferedWriter(destFile.toPath())) {
// write column names
content = new StringBuilder("");
for (int colIdx = 0; colIdx < colCount; colIdx++) {
content.append('"').append(tableModel.getColumnName(colIdx)).append('"');
if (colIdx < (colCount - 1)) {
content.append(",");
}
}
content.append(System.getProperty("line.separator"));
writer.write(content.toString());
// write rows
for (int rowViewIdx : selectedRowViewIndices) {
content = new StringBuilder("");
for (int colIdx = 0; colIdx < colCount; colIdx++) {
int rowModelIdx = otherCasesTable.convertRowIndexToModel(rowViewIdx);
content.append('"').append(tableModel.getValueAt(rowModelIdx, colIdx)).append('"');
if (colIdx < (colCount - 1)) {
content.append(",");
}
}
content.append(System.getProperty("line.separator"));
writer.write(content.toString());
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error writing selected rows to CSV.", ex);
}
}
/**
* Reset the UI and clear cached data.
*/
private void reset() {
// start with empty table
tableModel.clearTable();
correlationAttributes.clear();
}
@Override
public String getTitle() {
return Bundle.DataContentViewerOtherCases_title();
}
@Override
public String getToolTip() {
return Bundle.DataContentViewerOtherCases_toolTip();
}
@Override
public DataContentViewer createInstance() {
return new DataContentViewerOtherCases();
}
@Override
public Component getComponent() {
return this;
}
@Override
public void resetComponent() {
reset();
}
@Override
public int isPreferred(Node node) {
return 1;
}
/**
* Get the associated BlackboardArtifact from a node, if it exists.
*
* @param node The node
*
* @return The associated BlackboardArtifact, or null
*/
private BlackboardArtifact getBlackboardArtifactFromNode(Node node) {
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
BlackboardArtifact nodeBbArtifact = node.getLookup().lookup(BlackboardArtifact.class);
if (nodeBbArtifactTag != null) {
return nodeBbArtifactTag.getArtifact();
} else if (nodeBbArtifact != null) {
return nodeBbArtifact;
}
return null;
}
/**
* Get the associated AbstractFile from a node, if it exists.
*
* @param node The node
*
* @return The associated AbstractFile, or null
*/
private AbstractFile getAbstractFileFromNode(Node node) {
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
BlackboardArtifact nodeBbArtifact = node.getLookup().lookup(BlackboardArtifact.class);
AbstractFile nodeAbstractFile = node.getLookup().lookup(AbstractFile.class);
if (nodeBbArtifactTag != null) {
Content content = nodeBbArtifactTag.getContent();
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeContentTag != null) {
Content content = nodeContentTag.getContent();
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeBbArtifact != null) {
Content content;
try {
content = nodeBbArtifact.getSleuthkitCase().getContentById(nodeBbArtifact.getObjectID());
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Error retrieving blackboard artifact", ex); // NON-NLS
return null;
}
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeAbstractFile != null) {
return nodeAbstractFile;
}
return null;
}
/**
* Determine what attributes can be used for correlation based on the node.
* If EamDB is not enabled, get the default Files correlation.
*
* @param node The node to correlate
*
* @return A list of attributes that can be used for correlation
*/
private Collection<CorrelationAttribute> getCorrelationAttributesFromNode(Node node) {
Collection<CorrelationAttribute> ret = new ArrayList<>();
// correlate on blackboard artifact attributes if they exist and supported
BlackboardArtifact bbArtifact = getBlackboardArtifactFromNode(node);
if (bbArtifact != null) {
ret.addAll(EamArtifactUtil.getCorrelationAttributeFromBlackboardArtifact(bbArtifact, false, false));
}
// we can correlate based on the MD5 if it is enabled
if (this.file != null && EamDb.isEnabled()) {
try {
List<CorrelationAttribute.Type> artifactTypes = EamDb.getInstance().getDefinedCorrelationTypes();
String md5 = this.file.getMd5Hash();
if (md5 != null && !md5.isEmpty() && null != artifactTypes && !artifactTypes.isEmpty()) {
for (CorrelationAttribute.Type aType : artifactTypes) {
if (aType.getId() == CorrelationAttribute.FILES_TYPE_ID) {
ret.add(new CorrelationAttribute(aType, md5));
break;
}
}
}
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
}
} else {
try {
// If EamDb not enabled, get the Files default correlation type to allow Other Occurances to be enabled.
ret.add(new CorrelationAttribute(CorrelationAttribute.getDefaultCorrelationTypes().get(0), this.file.getMd5Hash()));
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
}
}
return ret;
}
/**
* Query the db for artifact instances from other cases correlated to the
* given central repository artifact. Will not show instances from the same
* datasource / device
*
* @param corAttr CorrelationAttribute to query for
* @param dataSourceName Data source to filter results
* @param deviceId Device Id to filter results
*
* @return A collection of correlated artifact instances from other cases
*/
private Map<ArtifactKey, CorrelationAttributeInstance> getCorrelatedInstances(CorrelationAttribute corAttr, String dataSourceName, String deviceId) {
// @@@ Check exception
try {
String caseUUID = Case.getOpenCase().getName();
Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances = new HashMap<>();
if (EamDb.isEnabled()) {
EamDb dbManager = EamDb.getInstance();
artifactInstances.putAll(dbManager.getArtifactInstancesByTypeValue(corAttr.getCorrelationType(), corAttr.getCorrelationValue()).stream()
.filter(artifactInstance -> !artifactInstance.getCorrelationCase().getCaseUUID().equals(caseUUID)
|| !artifactInstance.getCorrelationDataSource().getName().equals(dataSourceName)
|| !artifactInstance.getCorrelationDataSource().getDeviceID().equals(deviceId))
.collect(Collectors.toMap(c -> new ArtifactKey(c), c -> c)));
}
AddCaseDbMatches(corAttr, artifactInstances);
return artifactInstances;
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error getting artifact instances from database.", ex); // NON-NLS
} catch (NoCurrentCaseException ex) {
LOGGER.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
} catch (TskCoreException ex) {
// do nothing.
// @@@ Review this behavior
}
return new HashMap<>(0);
}
private void AddCaseDbMatches(CorrelationAttribute corAttr, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances) throws NoCurrentCaseException, TskCoreException, EamDbException {
if (corAttr.getCorrelationType().getDisplayName().equals("Files")) {
String md5 = corAttr.getCorrelationValue();
final Case openCase = Case.getOpenCase();
SleuthkitCase tsk = openCase.getSleuthkitCase();
List<AbstractFile> matches = tsk.findAllFilesWhere(String.format("md5 = '%s'", new Object[]{md5}));
CorrelationCase caze = new CorrelationCase(openCase.getNumber(), openCase.getDisplayName());
for (AbstractFile fileMatch : matches) {
if (this.file.equals(fileMatch)) {
continue; // If this is the file the user clicked on
}
AddOrUpdateAttributeInstance(caze, artifactInstances, openCase, fileMatch); // Determine whether to add fileMatch based on known status
}
}
}
private void AddOrUpdateAttributeInstance(CorrelationCase caze, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, final Case openCase, AbstractFile fileMatch) throws EamDbException, TskCoreException {
TskData.FileKnown knownStatus = fileMatch.getKnown();
CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, fileMatch.getDataSource());
String filePath = fileMatch.getParentPath() + fileMatch.getName();
ArtifactKey instKey = new ArtifactKey(dataSource.getDeviceID(), filePath);
// If not known, check Tags for known and set
if (knownStatus.compareTo(TskData.FileKnown.KNOWN) != 0 && knownStatus.compareTo(TskData.FileKnown.BAD) != 0) {
List<ContentTag> fileMatchTags = openCase.getServices().getTagsManager().getContentTagsByContent(fileMatch);
for (ContentTag tag : fileMatchTags) {
TskData.FileKnown tagKnownStatus = tag.getName().getKnownStatus();
if (tagKnownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || tagKnownStatus.compareTo(TskData.FileKnown.BAD) == 0) {
knownStatus = TskData.FileKnown.BAD;
break;
}
}
}
// If known, or not in CR, add
if (knownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || knownStatus.compareTo(TskData.FileKnown.BAD) == 0 || !artifactInstances.containsKey(instKey)) {
CorrelationAttributeInstance inst = new CorrelationAttributeInstance(caze, dataSource, filePath, "", knownStatus);
artifactInstances.put(instKey, inst);
}
}
@Override
public boolean isSupported(Node node) {
this.file = this.getAbstractFileFromNode(node);
// Is supported if this node
// has correlatable content (File, BlackboardArtifact) OR
// other common files across datasources.
return this.file != null
&& this.file.getSize() > 0
&& !getCorrelationAttributesFromNode(node).isEmpty();
}
@Override
@Messages({"DataContentViewerOtherCases.table.nodbconnection=Cannot connect to central repository database."})
public void setNode(Node node) {
reset(); // reset the table to empty.
if (node == null) {
return;
}
//could be null
this.file = this.getAbstractFileFromNode(node);
populateTable(node);
}
/**
* Load the correlatable data into the table model. If there is no data
* available display the message on the status panel.
*
* @param node The node being viewed.
*/
@Messages({"DataContentViewerOtherCases.table.isempty=There are no associated artifacts or files from other occurrences to display.",
"DataContentViewerOtherCases.table.noArtifacts=Correlation cannot be performed on the selected file."})
private void populateTable(Node node) {
String dataSourceName = "";
String deviceId = "";
try {
if (this.file != null) {
Content dataSource = this.file.getDataSource();
dataSourceName = dataSource.getName();
deviceId = Case.getOpenCase().getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
}
} catch (TskException | NoCurrentCaseException ex) {
// do nothing.
// @@@ Review this behavior
}
// get the attributes we can correlate on
correlationAttributes.addAll(getCorrelationAttributesFromNode(node));
for (CorrelationAttribute corAttr : correlationAttributes) {
Map<ArtifactKey, CorrelationAttributeInstance> corAttrInstances = new HashMap<>(0);
// get correlation and reference set instances from DB
corAttrInstances.putAll(getCorrelatedInstances(corAttr, dataSourceName, deviceId));
corAttrInstances.values().forEach((corAttrInstance) -> {
try {
CorrelationAttribute newCeArtifact = new CorrelationAttribute(
corAttr.getCorrelationType(),
corAttr.getCorrelationValue()
);
newCeArtifact.addInstance(corAttrInstance);
tableModel.addEamArtifact(newCeArtifact);
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error creating correlation attribute", ex);
}
});
}
if (correlationAttributes.isEmpty()) {
displayMessageOnTableStatusPanel(Bundle.DataContentViewerOtherCases_table_noArtifacts());
} else if (0 == tableModel.getRowCount()) {
displayMessageOnTableStatusPanel(Bundle.DataContentViewerOtherCases_table_isempty());
} else {
clearMessageOnTableStatusPanel();
setColumnWidths();
}
}
private void setColumnWidths() {
for (int idx = 0; idx < tableModel.getColumnCount(); idx++) {
TableColumn column = otherCasesTable.getColumnModel().getColumn(idx);
int colWidth = tableModel.getColumnPreferredWidth(idx);
if (0 < colWidth) {
column.setPreferredWidth(colWidth);
}
}
}
private void displayMessageOnTableStatusPanel(String message) {
tableStatusPanelLabel.setText(message);
tableStatusPanelLabel.setVisible(true);
}
private void clearMessageOnTableStatusPanel() {
tableStatusPanelLabel.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
rightClickPopupMenu = new javax.swing.JPopupMenu();
selectAllMenuItem = new javax.swing.JMenuItem();
exportToCSVMenuItem = new javax.swing.JMenuItem();
showCaseDetailsMenuItem = new javax.swing.JMenuItem();
showCommonalityMenuItem = new javax.swing.JMenuItem();
CSVFileChooser = new javax.swing.JFileChooser();
otherCasesPanel = new javax.swing.JPanel();
tableContainerPanel = new javax.swing.JPanel();
tableScrollPane = new javax.swing.JScrollPane();
otherCasesTable = new javax.swing.JTable();
tableStatusPanel = new javax.swing.JPanel();
tableStatusPanelLabel = new javax.swing.JLabel();
org.openide.awt.Mnemonics.setLocalizedText(selectAllMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.selectAllMenuItem.text")); // NOI18N
rightClickPopupMenu.add(selectAllMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(exportToCSVMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.exportToCSVMenuItem.text")); // NOI18N
rightClickPopupMenu.add(exportToCSVMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(showCaseDetailsMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.showCaseDetailsMenuItem.text")); // NOI18N
rightClickPopupMenu.add(showCaseDetailsMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(showCommonalityMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.showCommonalityMenuItem.text")); // NOI18N
rightClickPopupMenu.add(showCommonalityMenuItem);
setMinimumSize(new java.awt.Dimension(1500, 10));
setOpaque(false);
setPreferredSize(new java.awt.Dimension(1500, 44));
otherCasesPanel.setPreferredSize(new java.awt.Dimension(1500, 144));
tableContainerPanel.setPreferredSize(new java.awt.Dimension(1500, 63));
tableScrollPane.setPreferredSize(new java.awt.Dimension(1500, 30));
otherCasesTable.setAutoCreateRowSorter(true);
otherCasesTable.setModel(tableModel);
otherCasesTable.setToolTipText(org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.table.toolTip.text")); // NOI18N
otherCasesTable.setComponentPopupMenu(rightClickPopupMenu);
otherCasesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tableScrollPane.setViewportView(otherCasesTable);
tableStatusPanel.setPreferredSize(new java.awt.Dimension(1500, 16));
tableStatusPanelLabel.setForeground(new java.awt.Color(255, 0, 51));
javax.swing.GroupLayout tableStatusPanelLayout = new javax.swing.GroupLayout(tableStatusPanel);
tableStatusPanel.setLayout(tableStatusPanelLayout);
tableStatusPanelLayout.setHorizontalGroup(
tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableStatusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(tableStatusPanelLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
.addContainerGap()))
);
tableStatusPanelLayout.setVerticalGroup(
tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 16, Short.MAX_VALUE)
.addGroup(tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableStatusPanelLayout.createSequentialGroup()
.addComponent(tableStatusPanelLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
javax.swing.GroupLayout tableContainerPanelLayout = new javax.swing.GroupLayout(tableContainerPanel);
tableContainerPanel.setLayout(tableContainerPanelLayout);
tableContainerPanelLayout.setHorizontalGroup(
tableContainerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tableScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tableStatusPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
tableContainerPanelLayout.setVerticalGroup(
tableContainerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableContainerPanelLayout.createSequentialGroup()
.addComponent(tableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tableStatusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout otherCasesPanelLayout = new javax.swing.GroupLayout(otherCasesPanel);
otherCasesPanel.setLayout(otherCasesPanelLayout);
otherCasesPanelLayout.setHorizontalGroup(
otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1500, Short.MAX_VALUE)
.addGroup(otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tableContainerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
otherCasesPanelLayout.setVerticalGroup(
otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
.addGroup(otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(otherCasesPanelLayout.createSequentialGroup()
.addComponent(tableContainerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
.addGap(0, 0, 0)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(otherCasesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(otherCasesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFileChooser CSVFileChooser;
private javax.swing.JMenuItem exportToCSVMenuItem;
private javax.swing.JPanel otherCasesPanel;
private javax.swing.JTable otherCasesTable;
private javax.swing.JPopupMenu rightClickPopupMenu;
private javax.swing.JMenuItem selectAllMenuItem;
private javax.swing.JMenuItem showCaseDetailsMenuItem;
private javax.swing.JMenuItem showCommonalityMenuItem;
private javax.swing.JPanel tableContainerPanel;
private javax.swing.JScrollPane tableScrollPane;
private javax.swing.JPanel tableStatusPanel;
private javax.swing.JLabel tableStatusPanelLabel;
// End of variables declaration//GEN-END:variables
}
| Core/src/org/sleuthkit/autopsy/centralrepository/contentviewer/DataContentViewerOtherCases.java | /*
* Central Repository
*
* Copyright 2015-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.centralrepository.contentviewer;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import java.util.stream.Collectors;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.DEFAULT_OPTION;
import static javax.swing.JOptionPane.PLAIN_MESSAGE;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.openide.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContentViewer;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttribute;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamArtifactUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationDataSource;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskException;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskData;
/**
* View correlation results from other cases
*/
@ServiceProvider(service = DataContentViewer.class, position = 8)
@Messages({"DataContentViewerOtherCases.title=Other Occurrences",
"DataContentViewerOtherCases.toolTip=Displays instances of the selected file/artifact from other occurrences.",})
public class DataContentViewerOtherCases extends javax.swing.JPanel implements DataContentViewer {
private final static Logger LOGGER = Logger.getLogger(DataContentViewerOtherCases.class.getName());
private final DataContentViewerOtherCasesTableModel tableModel;
private final Collection<CorrelationAttribute> correlationAttributes;
/**
* Could be null.
*/
private AbstractFile file;
/**
* Creates new form DataContentViewerOtherCases
*/
public DataContentViewerOtherCases() {
this.tableModel = new DataContentViewerOtherCasesTableModel();
this.correlationAttributes = new ArrayList<>();
initComponents();
customizeComponents();
reset();
}
private void customizeComponents() {
ActionListener actList = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem jmi = (JMenuItem) e.getSource();
if (jmi.equals(selectAllMenuItem)) {
otherCasesTable.selectAll();
} else if (jmi.equals(showCaseDetailsMenuItem)) {
showCaseDetails(otherCasesTable.getSelectedRow());
} else if (jmi.equals(exportToCSVMenuItem)) {
try {
saveToCSV();
} catch (NoCurrentCaseException ex) {
LOGGER.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
}
} else if (jmi.equals(showCommonalityMenuItem)) {
showCommonalityDetails();
}
}
};
exportToCSVMenuItem.addActionListener(actList);
selectAllMenuItem.addActionListener(actList);
showCaseDetailsMenuItem.addActionListener(actList);
showCommonalityMenuItem.addActionListener(actList);
// Set background of every nth row as light grey.
TableCellRenderer renderer = new DataContentViewerOtherCasesTableCellRenderer();
otherCasesTable.setDefaultRenderer(Object.class, renderer);
tableStatusPanelLabel.setVisible(false);
}
@Messages({"DataContentViewerOtherCases.correlatedArtifacts.isEmpty=There are no files or artifacts to correlate.",
"# {0} - commonality percentage",
"# {1} - correlation type",
"# {2} - correlation value",
"DataContentViewerOtherCases.correlatedArtifacts.byType={0}% of data sources have {2} (type: {1})\n",
"DataContentViewerOtherCases.correlatedArtifacts.title=Attribute Frequency",
"DataContentViewerOtherCases.correlatedArtifacts.failed=Failed to get frequency details."})
/**
* Show how common the selected
*/
private void showCommonalityDetails() {
if (correlationAttributes.isEmpty()) {
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
Bundle.DataContentViewerOtherCases_correlatedArtifacts_isEmpty(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, PLAIN_MESSAGE);
} else {
StringBuilder msg = new StringBuilder();
int percentage;
try {
EamDb dbManager = EamDb.getInstance();
for (CorrelationAttribute eamArtifact : correlationAttributes) {
percentage = dbManager.getFrequencyPercentage(eamArtifact);
msg.append(Bundle.DataContentViewerOtherCases_correlatedArtifacts_byType(percentage,
eamArtifact.getCorrelationType().getDisplayName(),
eamArtifact.getCorrelationValue()));
}
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
msg.toString(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, PLAIN_MESSAGE);
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error getting commonality details.", ex);
JOptionPane.showConfirmDialog(showCommonalityMenuItem,
Bundle.DataContentViewerOtherCases_correlatedArtifacts_failed(),
Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(),
DEFAULT_OPTION, ERROR_MESSAGE);
}
}
}
@Messages({"DataContentViewerOtherCases.caseDetailsDialog.notSelected=No Row Selected",
"DataContentViewerOtherCases.caseDetailsDialog.noDetails=No details for this case.",
"DataContentViewerOtherCases.caseDetailsDialog.noDetailsReference=No case details for Global reference properties.",
"DataContentViewerOtherCases.caseDetailsDialog.noCaseNameError=Error",
"DataContentViewerOtherCases.noOpenCase.errMsg=No open case available."})
private void showCaseDetails(int selectedRowViewIdx) {
Case openCase;
try {
openCase = Case.getOpenCase();
} catch (NoCurrentCaseException ex) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_noOpenCase_errMsg(),
Bundle.DataContentViewerOtherCases_noOpenCase_errMsg(),
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
String caseDisplayName = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noCaseNameError();
try {
if (-1 != selectedRowViewIdx) {
EamDb dbManager = EamDb.getInstance();
int selectedRowModelIdx = otherCasesTable.convertRowIndexToModel(selectedRowViewIdx);
CorrelationAttribute eamArtifact = (CorrelationAttribute) tableModel.getRow(selectedRowModelIdx);
CorrelationCase eamCasePartial = eamArtifact.getInstances().get(0).getCorrelationCase();
if (eamCasePartial == null) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetailsReference(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
caseDisplayName = eamCasePartial.getDisplayName();
// query case details
CorrelationCase eamCase = dbManager.getCase(openCase);
if (eamCase == null) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
return;
}
// display case details
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
eamCase.getCaseDetailsOptionsPaneDialog(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
} else {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_notSelected(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
}
} catch (EamDbException ex) {
JOptionPane.showConfirmDialog(showCaseDetailsMenuItem,
Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(),
caseDisplayName,
DEFAULT_OPTION, PLAIN_MESSAGE);
}
}
private void saveToCSV() throws NoCurrentCaseException {
if (0 != otherCasesTable.getSelectedRowCount()) {
Calendar now = Calendar.getInstance();
String fileName = String.format("%1$tY%1$tm%1$te%1$tI%1$tM%1$tS_other_data_sources.csv", now);
CSVFileChooser.setCurrentDirectory(new File(Case.getOpenCase().getExportDirectory()));
CSVFileChooser.setSelectedFile(new File(fileName));
CSVFileChooser.setFileFilter(new FileNameExtensionFilter("csv file", "csv"));
int returnVal = CSVFileChooser.showSaveDialog(otherCasesTable);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = CSVFileChooser.getSelectedFile();
if (!selectedFile.getName().endsWith(".csv")) { // NON-NLS
selectedFile = new File(selectedFile.toString() + ".csv"); // NON-NLS
}
writeSelectedRowsToFileAsCSV(selectedFile);
}
}
}
private void writeSelectedRowsToFileAsCSV(File destFile) {
StringBuilder content;
int[] selectedRowViewIndices = otherCasesTable.getSelectedRows();
int colCount = tableModel.getColumnCount();
try (BufferedWriter writer = Files.newBufferedWriter(destFile.toPath())) {
// write column names
content = new StringBuilder("");
for (int colIdx = 0; colIdx < colCount; colIdx++) {
content.append('"').append(tableModel.getColumnName(colIdx)).append('"');
if (colIdx < (colCount - 1)) {
content.append(",");
}
}
content.append(System.getProperty("line.separator"));
writer.write(content.toString());
// write rows
for (int rowViewIdx : selectedRowViewIndices) {
content = new StringBuilder("");
for (int colIdx = 0; colIdx < colCount; colIdx++) {
int rowModelIdx = otherCasesTable.convertRowIndexToModel(rowViewIdx);
content.append('"').append(tableModel.getValueAt(rowModelIdx, colIdx)).append('"');
if (colIdx < (colCount - 1)) {
content.append(",");
}
}
content.append(System.getProperty("line.separator"));
writer.write(content.toString());
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error writing selected rows to CSV.", ex);
}
}
/**
* Reset the UI and clear cached data.
*/
private void reset() {
// start with empty table
tableModel.clearTable();
correlationAttributes.clear();
}
@Override
public String getTitle() {
return Bundle.DataContentViewerOtherCases_title();
}
@Override
public String getToolTip() {
return Bundle.DataContentViewerOtherCases_toolTip();
}
@Override
public DataContentViewer createInstance() {
return new DataContentViewerOtherCases();
}
@Override
public Component getComponent() {
return this;
}
@Override
public void resetComponent() {
reset();
}
@Override
public int isPreferred(Node node) {
return 1;
}
/**
* Get the associated BlackboardArtifact from a node, if it exists.
*
* @param node The node
*
* @return The associated BlackboardArtifact, or null
*/
private BlackboardArtifact getBlackboardArtifactFromNode(Node node) {
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
BlackboardArtifact nodeBbArtifact = node.getLookup().lookup(BlackboardArtifact.class);
if (nodeBbArtifactTag != null) {
return nodeBbArtifactTag.getArtifact();
} else if (nodeBbArtifact != null) {
return nodeBbArtifact;
}
return null;
}
/**
* Get the associated AbstractFile from a node, if it exists.
*
* @param node The node
*
* @return The associated AbstractFile, or null
*/
private AbstractFile getAbstractFileFromNode(Node node) {
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
BlackboardArtifact nodeBbArtifact = node.getLookup().lookup(BlackboardArtifact.class);
AbstractFile nodeAbstractFile = node.getLookup().lookup(AbstractFile.class);
if (nodeBbArtifactTag != null) {
Content content = nodeBbArtifactTag.getContent();
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeContentTag != null) {
Content content = nodeContentTag.getContent();
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeBbArtifact != null) {
Content content;
try {
content = nodeBbArtifact.getSleuthkitCase().getContentById(nodeBbArtifact.getObjectID());
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Error retrieving blackboard artifact", ex); // NON-NLS
return null;
}
if (content instanceof AbstractFile) {
return (AbstractFile) content;
}
} else if (nodeAbstractFile != null) {
return nodeAbstractFile;
}
return null;
}
/**
* Determine what attributes can be used for correlation based on the node.
* If EamDB is not enabled, get the default Files correlation.
*
* @param node The node to correlate
*
* @return A list of attributes that can be used for correlation
*/
private Collection<CorrelationAttribute> getCorrelationAttributesFromNode(Node node) {
Collection<CorrelationAttribute> ret = new ArrayList<>();
// correlate on blackboard artifact attributes if they exist and supported
BlackboardArtifact bbArtifact = getBlackboardArtifactFromNode(node);
if (bbArtifact != null) {
ret.addAll(EamArtifactUtil.getCorrelationAttributeFromBlackboardArtifact(bbArtifact, false, false));
}
// we can correlate based on the MD5 if it is enabled
if (this.file != null && EamDb.isEnabled()) {
try {
List<CorrelationAttribute.Type> artifactTypes = EamDb.getInstance().getDefinedCorrelationTypes();
String md5 = this.file.getMd5Hash();
if (md5 != null && !md5.isEmpty() && null != artifactTypes && !artifactTypes.isEmpty()) {
for (CorrelationAttribute.Type aType : artifactTypes) {
if (aType.getId() == CorrelationAttribute.FILES_TYPE_ID) {
ret.add(new CorrelationAttribute(aType, md5));
break;
}
}
}
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
}
} else {
try {
// If EamDb not enabled, get the Files default correlation type to allow Other Occurances to be enabled.
ret.add(new CorrelationAttribute(CorrelationAttribute.getDefaultCorrelationTypes().get(0), this.file.getMd5Hash()));
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
}
}
return ret;
}
/**
* Query the db for artifact instances from other cases correlated to the
* given central repository artifact. Will not show instances from the same
* datasource / device
*
* @param corAttr CorrelationAttribute to query for
* @param dataSourceName Data source to filter results
* @param deviceId Device Id to filter results
*
* @return A collection of correlated artifact instances from other cases
*/
private Map<ArtifactKey, CorrelationAttributeInstance> getCorrelatedInstances(CorrelationAttribute corAttr, String dataSourceName, String deviceId) {
// @@@ Check exception
try {
String caseUUID = Case.getOpenCase().getName();
Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances = new HashMap<>();
if (EamDb.isEnabled()) {
EamDb dbManager = EamDb.getInstance();
artifactInstances.putAll(dbManager.getArtifactInstancesByTypeValue(corAttr.getCorrelationType(), corAttr.getCorrelationValue()).stream()
.filter(artifactInstance -> !artifactInstance.getCorrelationCase().getCaseUUID().equals(caseUUID)
|| !artifactInstance.getCorrelationDataSource().getName().equals(dataSourceName)
|| !artifactInstance.getCorrelationDataSource().getDeviceID().equals(deviceId))
.collect(Collectors.toMap(c -> new ArtifactKey(c), c -> c)));
}
AddCaseDbMatches(corAttr, artifactInstances);
return artifactInstances;
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error getting artifact instances from database.", ex); // NON-NLS
} catch (NoCurrentCaseException ex) {
LOGGER.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
} catch (TskCoreException ex) {
// do nothing.
// @@@ Review this behavior
}
return new HashMap<>(0);
}
private void AddCaseDbMatches(CorrelationAttribute corAttr, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances) throws NoCurrentCaseException, TskCoreException, EamDbException {
if (corAttr.getCorrelationType().getDisplayName().equals("Files")) {
String md5 = corAttr.getCorrelationValue();
final Case openCase = Case.getOpenCase();
SleuthkitCase tsk = openCase.getSleuthkitCase();
List<AbstractFile> matches = tsk.findAllFilesWhere(String.format("md5 = '%s'", new Object[]{md5}));
CorrelationCase caze = new CorrelationCase(openCase.getNumber(), openCase.getDisplayName());
for (AbstractFile fileMatch : matches) {
if (this.file.equals(fileMatch)) {
continue; // If this is the file the user clicked on
}
CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, fileMatch.getDataSource());
AddCheckKnownStatus(caze, dataSource, artifactInstances, openCase, fileMatch);
}
}
}
private void AddCheckKnownStatus(CorrelationCase caze, CorrelationDataSource dataSource, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, final Case openCase, AbstractFile fileMatch) throws EamDbException, TskCoreException {
TskData.FileKnown knownStatus = fileMatch.getKnown();
String filePath = fileMatch.getParentPath() + fileMatch.getName();
ArtifactKey instKey = new ArtifactKey(dataSource.getDeviceID(), filePath);
// If not known, check Tags for known and set
if (knownStatus.compareTo(TskData.FileKnown.KNOWN) != 0 && knownStatus.compareTo(TskData.FileKnown.BAD) != 0) {
List<ContentTag> fileMatchTags = openCase.getServices().getTagsManager().getContentTagsByContent(fileMatch);
for (ContentTag tag : fileMatchTags) {
TskData.FileKnown tagKnownStatus = tag.getName().getKnownStatus();
if (tagKnownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || tagKnownStatus.compareTo(TskData.FileKnown.BAD) == 0) {
knownStatus = TskData.FileKnown.BAD;
break;
}
}
}
// If known, or not in CR, add
if (knownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || knownStatus.compareTo(TskData.FileKnown.BAD) == 0 || !artifactInstances.containsKey(instKey)) {
CorrelationAttributeInstance inst = new CorrelationAttributeInstance(caze, dataSource, filePath, "", knownStatus);
artifactInstances.put(instKey, inst);
}
}
@Override
public boolean isSupported(Node node) {
this.file = this.getAbstractFileFromNode(node);
// Is supported if this node
// has correlatable content (File, BlackboardArtifact) OR
// other common files across datasources.
return this.file != null
&& this.file.getSize() > 0
&& !getCorrelationAttributesFromNode(node).isEmpty();
}
@Override
@Messages({"DataContentViewerOtherCases.table.nodbconnection=Cannot connect to central repository database."})
public void setNode(Node node) {
reset(); // reset the table to empty.
if (node == null) {
return;
}
//could be null
this.file = this.getAbstractFileFromNode(node);
populateTable(node);
}
/**
* Load the correlatable data into the table model. If there is no data
* available display the message on the status panel.
*
* @param node The node being viewed.
*/
@Messages({"DataContentViewerOtherCases.table.isempty=There are no associated artifacts or files from other occurrences to display.",
"DataContentViewerOtherCases.table.noArtifacts=Correlation cannot be performed on the selected file."})
private void populateTable(Node node) {
String dataSourceName = "";
String deviceId = "";
try {
if (this.file != null) {
Content dataSource = this.file.getDataSource();
dataSourceName = dataSource.getName();
deviceId = Case.getOpenCase().getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
}
} catch (TskException | NoCurrentCaseException ex) {
// do nothing.
// @@@ Review this behavior
}
// get the attributes we can correlate on
correlationAttributes.addAll(getCorrelationAttributesFromNode(node));
for (CorrelationAttribute corAttr : correlationAttributes) {
Map<ArtifactKey, CorrelationAttributeInstance> corAttrInstances = new HashMap<>(0);
// get correlation and reference set instances from DB
corAttrInstances.putAll(getCorrelatedInstances(corAttr, dataSourceName, deviceId));
corAttrInstances.values().forEach((corAttrInstance) -> {
try {
CorrelationAttribute newCeArtifact = new CorrelationAttribute(
corAttr.getCorrelationType(),
corAttr.getCorrelationValue()
);
newCeArtifact.addInstance(corAttrInstance);
tableModel.addEamArtifact(newCeArtifact);
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error creating correlation attribute", ex);
}
});
}
if (correlationAttributes.isEmpty()) {
displayMessageOnTableStatusPanel(Bundle.DataContentViewerOtherCases_table_noArtifacts());
} else if (0 == tableModel.getRowCount()) {
displayMessageOnTableStatusPanel(Bundle.DataContentViewerOtherCases_table_isempty());
} else {
clearMessageOnTableStatusPanel();
setColumnWidths();
}
}
private void setColumnWidths() {
for (int idx = 0; idx < tableModel.getColumnCount(); idx++) {
TableColumn column = otherCasesTable.getColumnModel().getColumn(idx);
int colWidth = tableModel.getColumnPreferredWidth(idx);
if (0 < colWidth) {
column.setPreferredWidth(colWidth);
}
}
}
private void displayMessageOnTableStatusPanel(String message) {
tableStatusPanelLabel.setText(message);
tableStatusPanelLabel.setVisible(true);
}
private void clearMessageOnTableStatusPanel() {
tableStatusPanelLabel.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
rightClickPopupMenu = new javax.swing.JPopupMenu();
selectAllMenuItem = new javax.swing.JMenuItem();
exportToCSVMenuItem = new javax.swing.JMenuItem();
showCaseDetailsMenuItem = new javax.swing.JMenuItem();
showCommonalityMenuItem = new javax.swing.JMenuItem();
CSVFileChooser = new javax.swing.JFileChooser();
otherCasesPanel = new javax.swing.JPanel();
tableContainerPanel = new javax.swing.JPanel();
tableScrollPane = new javax.swing.JScrollPane();
otherCasesTable = new javax.swing.JTable();
tableStatusPanel = new javax.swing.JPanel();
tableStatusPanelLabel = new javax.swing.JLabel();
org.openide.awt.Mnemonics.setLocalizedText(selectAllMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.selectAllMenuItem.text")); // NOI18N
rightClickPopupMenu.add(selectAllMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(exportToCSVMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.exportToCSVMenuItem.text")); // NOI18N
rightClickPopupMenu.add(exportToCSVMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(showCaseDetailsMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.showCaseDetailsMenuItem.text")); // NOI18N
rightClickPopupMenu.add(showCaseDetailsMenuItem);
org.openide.awt.Mnemonics.setLocalizedText(showCommonalityMenuItem, org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.showCommonalityMenuItem.text")); // NOI18N
rightClickPopupMenu.add(showCommonalityMenuItem);
setMinimumSize(new java.awt.Dimension(1500, 10));
setOpaque(false);
setPreferredSize(new java.awt.Dimension(1500, 44));
otherCasesPanel.setPreferredSize(new java.awt.Dimension(1500, 144));
tableContainerPanel.setPreferredSize(new java.awt.Dimension(1500, 63));
tableScrollPane.setPreferredSize(new java.awt.Dimension(1500, 30));
otherCasesTable.setAutoCreateRowSorter(true);
otherCasesTable.setModel(tableModel);
otherCasesTable.setToolTipText(org.openide.util.NbBundle.getMessage(DataContentViewerOtherCases.class, "DataContentViewerOtherCases.table.toolTip.text")); // NOI18N
otherCasesTable.setComponentPopupMenu(rightClickPopupMenu);
otherCasesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tableScrollPane.setViewportView(otherCasesTable);
tableStatusPanel.setPreferredSize(new java.awt.Dimension(1500, 16));
tableStatusPanelLabel.setForeground(new java.awt.Color(255, 0, 51));
javax.swing.GroupLayout tableStatusPanelLayout = new javax.swing.GroupLayout(tableStatusPanel);
tableStatusPanel.setLayout(tableStatusPanelLayout);
tableStatusPanelLayout.setHorizontalGroup(
tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableStatusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(tableStatusPanelLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
.addContainerGap()))
);
tableStatusPanelLayout.setVerticalGroup(
tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 16, Short.MAX_VALUE)
.addGroup(tableStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableStatusPanelLayout.createSequentialGroup()
.addComponent(tableStatusPanelLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
javax.swing.GroupLayout tableContainerPanelLayout = new javax.swing.GroupLayout(tableContainerPanel);
tableContainerPanel.setLayout(tableContainerPanelLayout);
tableContainerPanelLayout.setHorizontalGroup(
tableContainerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tableScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tableStatusPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
tableContainerPanelLayout.setVerticalGroup(
tableContainerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tableContainerPanelLayout.createSequentialGroup()
.addComponent(tableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tableStatusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout otherCasesPanelLayout = new javax.swing.GroupLayout(otherCasesPanel);
otherCasesPanel.setLayout(otherCasesPanelLayout);
otherCasesPanelLayout.setHorizontalGroup(
otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1500, Short.MAX_VALUE)
.addGroup(otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tableContainerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
otherCasesPanelLayout.setVerticalGroup(
otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
.addGroup(otherCasesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(otherCasesPanelLayout.createSequentialGroup()
.addComponent(tableContainerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
.addGap(0, 0, 0)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(otherCasesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(otherCasesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFileChooser CSVFileChooser;
private javax.swing.JMenuItem exportToCSVMenuItem;
private javax.swing.JPanel otherCasesPanel;
private javax.swing.JTable otherCasesTable;
private javax.swing.JPopupMenu rightClickPopupMenu;
private javax.swing.JMenuItem selectAllMenuItem;
private javax.swing.JMenuItem showCaseDetailsMenuItem;
private javax.swing.JMenuItem showCommonalityMenuItem;
private javax.swing.JPanel tableContainerPanel;
private javax.swing.JScrollPane tableScrollPane;
private javax.swing.JPanel tableStatusPanel;
private javax.swing.JLabel tableStatusPanelLabel;
// End of variables declaration//GEN-END:variables
}
| Cleanup correlation case function.
| Core/src/org/sleuthkit/autopsy/centralrepository/contentviewer/DataContentViewerOtherCases.java | Cleanup correlation case function. | <ide><path>ore/src/org/sleuthkit/autopsy/centralrepository/contentviewer/DataContentViewerOtherCases.java
<ide> for (AbstractFile fileMatch : matches) {
<ide> if (this.file.equals(fileMatch)) {
<ide> continue; // If this is the file the user clicked on
<del> }
<del> CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, fileMatch.getDataSource());
<del> AddCheckKnownStatus(caze, dataSource, artifactInstances, openCase, fileMatch);
<del> }
<del> }
<del> }
<del>
<del> private void AddCheckKnownStatus(CorrelationCase caze, CorrelationDataSource dataSource, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, final Case openCase, AbstractFile fileMatch) throws EamDbException, TskCoreException {
<del> TskData.FileKnown knownStatus = fileMatch.getKnown();
<add> }
<add> AddOrUpdateAttributeInstance(caze, artifactInstances, openCase, fileMatch); // Determine whether to add fileMatch based on known status
<add> }
<add> }
<add> }
<add>
<add> private void AddOrUpdateAttributeInstance(CorrelationCase caze, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, final Case openCase, AbstractFile fileMatch) throws EamDbException, TskCoreException {
<add> TskData.FileKnown knownStatus = fileMatch.getKnown();
<add> CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, fileMatch.getDataSource());
<ide> String filePath = fileMatch.getParentPath() + fileMatch.getName();
<ide> ArtifactKey instKey = new ArtifactKey(dataSource.getDeviceID(), filePath);
<ide> // If not known, check Tags for known and set |
|
Java | mit | eb7ac1d080b2a881a0bed1c89f3adb93196b3f6e | 0 | tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus | /*******************************************************************************
* Copyright (c) 2019 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* 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.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package tlc2.value;
import java.io.IOException;
import tla2sany.semantic.SemanticNode;
import tlc2.tool.coverage.CostModel;
public interface IValue extends Comparable<Object> {
/* This method compares this with val. */
int compareTo(Object val);
void write(IValueOutputStream vos) throws IOException;
IValue setCostModel(CostModel cm);
CostModel getCostModel();
void setSource(SemanticNode semanticNode);
SemanticNode getSource();
boolean hasSource();
/**
* This method normalizes (destructively) the representation of
* the value. It is essential for equality comparison.
*/
boolean isNormalized();
/* Fully normalize this (composite) value. */
void deepNormalize();
/* This method returns the fingerprint of this value. */
long fingerPrint(long fp);
/**
* This method returns the value permuted by the permutation. It
* returns this if nothing is permuted.
*/
IValue permute(IMVPerm perm);
/* This method returns true iff the value is finite. */
boolean isFinite();
/* This method returns the size of the value. */
int size();
/* This method returns true iff the value is fully defined. */
boolean isDefined();
/* This method makes a real deep copy of this. */
IValue deepCopy();
/**
* This abstract method returns a string representation of this
* value. Each subclass must provide its own implementation.
*/
StringBuffer toString(StringBuffer sb, int offset, boolean swallow);
/* The string representation of this value */
String toString();
String toString(String delim);
} | tlatools/src/tlc2/value/IValue.java | /*******************************************************************************
* Copyright (c) 2019 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* 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.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package tlc2.value;
import java.io.IOException;
import tla2sany.semantic.SemanticNode;
import tlc2.tool.coverage.CostModel;
public interface IValue {
/* This method compares this with val. */
int compareTo(Object val);
void write(IValueOutputStream vos) throws IOException;
IValue setCostModel(CostModel cm);
CostModel getCostModel();
void setSource(SemanticNode semanticNode);
SemanticNode getSource();
boolean hasSource();
/**
* This method normalizes (destructively) the representation of
* the value. It is essential for equality comparison.
*/
boolean isNormalized();
/* Fully normalize this (composite) value. */
void deepNormalize();
/* This method returns the fingerprint of this value. */
long fingerPrint(long fp);
/**
* This method returns the value permuted by the permutation. It
* returns this if nothing is permuted.
*/
IValue permute(IMVPerm perm);
/* This method returns true iff the value is finite. */
boolean isFinite();
/* This method returns the size of the value. */
int size();
/* This method returns true iff the value is fully defined. */
boolean isDefined();
/* This method makes a real deep copy of this. */
IValue deepCopy();
/**
* This abstract method returns a string representation of this
* value. Each subclass must provide its own implementation.
*/
StringBuffer toString(StringBuffer sb, int offset, boolean swallow);
/* The string representation of this value */
String toString();
String toString(String delim);
} | Let IValue implement Comparable interface since it already comes with
compareTo(Object).
[Refactor][TLC] | tlatools/src/tlc2/value/IValue.java | Let IValue implement Comparable interface since it already comes with compareTo(Object). | <ide><path>latools/src/tlc2/value/IValue.java
<ide> import tla2sany.semantic.SemanticNode;
<ide> import tlc2.tool.coverage.CostModel;
<ide>
<del>public interface IValue {
<add>public interface IValue extends Comparable<Object> {
<ide>
<ide> /* This method compares this with val. */
<ide> int compareTo(Object val); |
|
Java | mit | 4c6ed07d3763c766be1076b5eeaa9d126a34177d | 0 | daniel-beck/jenkins,olivergondza/jenkins,batmat/jenkins,tangkun75/jenkins,recena/jenkins,wuwen5/jenkins,gitaccountforprashant/gittest,godfath3r/jenkins,christ66/jenkins,olivergondza/jenkins,azweb76/jenkins,olivergondza/jenkins,azweb76/jenkins,wuwen5/jenkins,escoem/jenkins,Vlatombe/jenkins,Jimilian/jenkins,stephenc/jenkins,tangkun75/jenkins,batmat/jenkins,protazy/jenkins,escoem/jenkins,fbelzunc/jenkins,christ66/jenkins,batmat/jenkins,ydubreuil/jenkins,bpzhang/jenkins,olivergondza/jenkins,aldaris/jenkins,v1v/jenkins,lilyJi/jenkins,ikedam/jenkins,protazy/jenkins,FarmGeek4Life/jenkins,lilyJi/jenkins,sathiya-mit/jenkins,ikedam/jenkins,stephenc/jenkins,jglick/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,alvarolobato/jenkins,hplatou/jenkins,hplatou/jenkins,Ykus/jenkins,bkmeneguello/jenkins,jenkinsci/jenkins,rlugojr/jenkins,daniel-beck/jenkins,jglick/jenkins,rlugojr/jenkins,Jimilian/jenkins,viqueen/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,DanielWeber/jenkins,tfennelly/jenkins,rsandell/jenkins,v1v/jenkins,Ykus/jenkins,jenkinsci/jenkins,Jimilian/jenkins,ikedam/jenkins,ikedam/jenkins,dariver/jenkins,ajshastri/jenkins,tfennelly/jenkins,azweb76/jenkins,kohsuke/hudson,patbos/jenkins,wuwen5/jenkins,alvarolobato/jenkins,ydubreuil/jenkins,fbelzunc/jenkins,damianszczepanik/jenkins,pjanouse/jenkins,viqueen/jenkins,rlugojr/jenkins,Vlatombe/jenkins,amuniz/jenkins,tangkun75/jenkins,protazy/jenkins,godfath3r/jenkins,dariver/jenkins,ikedam/jenkins,lilyJi/jenkins,recena/jenkins,v1v/jenkins,ajshastri/jenkins,Jochen-A-Fuerbacher/jenkins,jpbriend/jenkins,oleg-nenashev/jenkins,batmat/jenkins,andresrc/jenkins,sathiya-mit/jenkins,bpzhang/jenkins,rlugojr/jenkins,wuwen5/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,viqueen/jenkins,ajshastri/jenkins,rlugojr/jenkins,ErikVerheul/jenkins,hplatou/jenkins,amuniz/jenkins,ndeloof/jenkins,jglick/jenkins,daniel-beck/jenkins,Jimilian/jenkins,ydubreuil/jenkins,sathiya-mit/jenkins,hplatou/jenkins,protazy/jenkins,viqueen/jenkins,pjanouse/jenkins,rlugojr/jenkins,ikedam/jenkins,FarmGeek4Life/jenkins,Jochen-A-Fuerbacher/jenkins,NehemiahMi/jenkins,DanielWeber/jenkins,aldaris/jenkins,escoem/jenkins,rsandell/jenkins,ydubreuil/jenkins,tangkun75/jenkins,sathiya-mit/jenkins,godfath3r/jenkins,dariver/jenkins,sathiya-mit/jenkins,bkmeneguello/jenkins,patbos/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,viqueen/jenkins,bkmeneguello/jenkins,NehemiahMi/jenkins,rsandell/jenkins,fbelzunc/jenkins,ErikVerheul/jenkins,escoem/jenkins,alvarolobato/jenkins,alvarolobato/jenkins,ajshastri/jenkins,stephenc/jenkins,jpbriend/jenkins,lilyJi/jenkins,FarmGeek4Life/jenkins,andresrc/jenkins,jglick/jenkins,bkmeneguello/jenkins,tangkun75/jenkins,NehemiahMi/jenkins,fbelzunc/jenkins,patbos/jenkins,ndeloof/jenkins,alvarolobato/jenkins,gitaccountforprashant/gittest,stephenc/jenkins,Vlatombe/jenkins,patbos/jenkins,DanielWeber/jenkins,escoem/jenkins,olivergondza/jenkins,aldaris/jenkins,kohsuke/hudson,christ66/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,wuwen5/jenkins,batmat/jenkins,NehemiahMi/jenkins,olivergondza/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,ajshastri/jenkins,jenkinsci/jenkins,recena/jenkins,Ykus/jenkins,bpzhang/jenkins,ndeloof/jenkins,amuniz/jenkins,rlugojr/jenkins,ydubreuil/jenkins,daniel-beck/jenkins,jglick/jenkins,jenkinsci/jenkins,Ykus/jenkins,tangkun75/jenkins,kohsuke/hudson,fbelzunc/jenkins,tangkun75/jenkins,gitaccountforprashant/gittest,andresrc/jenkins,recena/jenkins,kohsuke/hudson,tfennelly/jenkins,dariver/jenkins,DanielWeber/jenkins,protazy/jenkins,ErikVerheul/jenkins,Jimilian/jenkins,Vlatombe/jenkins,jpbriend/jenkins,tfennelly/jenkins,NehemiahMi/jenkins,recena/jenkins,batmat/jenkins,v1v/jenkins,stephenc/jenkins,christ66/jenkins,lilyJi/jenkins,ajshastri/jenkins,tfennelly/jenkins,ajshastri/jenkins,damianszczepanik/jenkins,hplatou/jenkins,jpbriend/jenkins,rsandell/jenkins,Ykus/jenkins,jenkinsci/jenkins,pjanouse/jenkins,pjanouse/jenkins,godfath3r/jenkins,protazy/jenkins,viqueen/jenkins,aldaris/jenkins,aldaris/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,ErikVerheul/jenkins,pjanouse/jenkins,batmat/jenkins,FarmGeek4Life/jenkins,sathiya-mit/jenkins,dariver/jenkins,rsandell/jenkins,Jimilian/jenkins,aldaris/jenkins,andresrc/jenkins,azweb76/jenkins,v1v/jenkins,stephenc/jenkins,pjanouse/jenkins,patbos/jenkins,oleg-nenashev/jenkins,andresrc/jenkins,azweb76/jenkins,ikedam/jenkins,recena/jenkins,ydubreuil/jenkins,MarkEWaite/jenkins,jpbriend/jenkins,ndeloof/jenkins,godfath3r/jenkins,christ66/jenkins,alvarolobato/jenkins,NehemiahMi/jenkins,ErikVerheul/jenkins,Vlatombe/jenkins,gitaccountforprashant/gittest,hplatou/jenkins,kohsuke/hudson,lilyJi/jenkins,ikedam/jenkins,fbelzunc/jenkins,bkmeneguello/jenkins,viqueen/jenkins,escoem/jenkins,azweb76/jenkins,v1v/jenkins,NehemiahMi/jenkins,protazy/jenkins,sathiya-mit/jenkins,ydubreuil/jenkins,jglick/jenkins,olivergondza/jenkins,ndeloof/jenkins,MarkEWaite/jenkins,amuniz/jenkins,gitaccountforprashant/gittest,damianszczepanik/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,jglick/jenkins,Vlatombe/jenkins,Jimilian/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,bpzhang/jenkins,MarkEWaite/jenkins,lilyJi/jenkins,gitaccountforprashant/gittest,oleg-nenashev/jenkins,ndeloof/jenkins,alvarolobato/jenkins,tfennelly/jenkins,jenkinsci/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,jpbriend/jenkins,patbos/jenkins,damianszczepanik/jenkins,rsandell/jenkins,stephenc/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,patbos/jenkins,amuniz/jenkins,andresrc/jenkins,dariver/jenkins,ndeloof/jenkins,andresrc/jenkins,bpzhang/jenkins,daniel-beck/jenkins,hplatou/jenkins,rsandell/jenkins,tfennelly/jenkins,bpzhang/jenkins,kohsuke/hudson,wuwen5/jenkins,FarmGeek4Life/jenkins,bkmeneguello/jenkins,fbelzunc/jenkins,FarmGeek4Life/jenkins,ErikVerheul/jenkins,bpzhang/jenkins,christ66/jenkins,recena/jenkins,damianszczepanik/jenkins,godfath3r/jenkins,Jochen-A-Fuerbacher/jenkins,escoem/jenkins,FarmGeek4Life/jenkins,v1v/jenkins,amuniz/jenkins,jpbriend/jenkins,DanielWeber/jenkins,kohsuke/hudson,damianszczepanik/jenkins,dariver/jenkins,Ykus/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,ErikVerheul/jenkins,azweb76/jenkins,Ykus/jenkins,damianszczepanik/jenkins,aldaris/jenkins,amuniz/jenkins,bkmeneguello/jenkins,gitaccountforprashant/gittest,christ66/jenkins,kohsuke/hudson,rsandell/jenkins,wuwen5/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Red Hat, Inc., Seiji Sogabe, Stephen Connolly, Thomas J. Black, Tom Huybrechts, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;
import edu.umd.cs.findbugs.annotations.When;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher.ProcStarter;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.console.AnnotatedLargeText;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.FlyweightTask;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.WorkUnit;
import hudson.node_monitors.NodeMonitor;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.WorkspaceList;
import hudson.slaves.OfflineCause;
import hudson.slaves.OfflineCause.ByCLI;
import hudson.util.DaemonThreadFactory;
import hudson.util.EditDistance;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.RunList;
import hudson.util.Futures;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.security.MasterToSlaveCallable;
import jenkins.security.NotReallyRoleSensitiveCallable;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Represents the running state of a remote computer that holds {@link Executor}s.
*
* <p>
* {@link Executor}s on one {@link Computer} are transparently interchangeable
* (that is the definition of {@link Computer}).
*
* <p>
* This object is related to {@link Node} but they have some significant differences.
* {@link Computer} primarily works as a holder of {@link Executor}s, so
* if a {@link Node} is configured (probably temporarily) with 0 executors,
* you won't have a {@link Computer} object for it (except for the master node,
* which always gets its {@link Computer} in case we have no static executors and
* we need to run a {@link FlyweightTask} - see JENKINS-7291 for more discussion.)
*
* Also, even if you remove a {@link Node}, it takes time for the corresponding
* {@link Computer} to be removed, if some builds are already in progress on that
* node. Or when the node configuration is changed, unaffected {@link Computer} object
* remains intact, while all the {@link Node} objects will go away.
*
* <p>
* This object also serves UI (unlike {@link Node}), and can be used along with
* {@link TransientComputerActionFactory} to add {@link Action}s to {@link Computer}s.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public /*transient*/ abstract class Computer extends Actionable implements AccessControlled, ExecutorListener {
private final CopyOnWriteArrayList<Executor> executors = new CopyOnWriteArrayList<Executor>();
// TODO:
private final CopyOnWriteArrayList<OneOffExecutor> oneOffExecutors = new CopyOnWriteArrayList<OneOffExecutor>();
private int numExecutors;
/**
* Contains info about reason behind computer being offline.
*/
protected volatile OfflineCause offlineCause;
private long connectTime = 0;
/**
* True if Jenkins shouldn't start new builds on this node.
*/
private boolean temporarilyOffline;
/**
* {@link Node} object may be created and deleted independently
* from this object.
*/
protected String nodeName;
/**
* @see #getHostName()
*/
private volatile String cachedHostName;
private volatile boolean hostNameCached;
/**
* @see #getEnvironment()
*/
private volatile EnvVars cachedEnvironment;
private final WorkspaceList workspaceList = new WorkspaceList();
protected transient List<Action> transientActions;
protected final Object statusChangeLock = new Object();
/**
* Keeps track of stack traces to track the tremination requests for this computer.
*
* @since 1.607
* @see Executor#resetWorkUnit(String)
*/
private transient final List<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
/**
* This method captures the information of a request to terminate a computer instance. Method is public as
* it needs to be called from {@link AbstractCloudSlave} and {@link jenkins.model.Nodes}. In general you should
* not need to call this method directly, however if implementing a custom node type or a different path
* for removing nodes, it may make sense to call this method in order to capture the originating request.
*
* @since 1.607
*/
public void recordTermination() {
StaplerRequest request = Stapler.getCurrentRequest();
if (request != null) {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId(),
request.getRequestURL()
)
));
} else {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d]",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId()
)
));
}
}
/**
* Returns the list of captured termination requests for this Computer. This method is used by {@link Executor}
* to provide details on why a Computer was removed in-between work being scheduled against the {@link Executor}
* and the {@link Executor} starting to execute the task.
*
* @return the (possibly empty) list of termination requests.
* @see Executor#resetWorkUnit(String)
* @since 1.607
*/
public List<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(terminatedBy);
}
public Computer(Node node) {
setNode(node);
}
/**
* Returns list of all boxes {@link ComputerPanelBox}s.
*/
public List<ComputerPanelBox> getComputerPanelBoxs(){
return ComputerPanelBox.all(this);
}
/**
* Returns the transient {@link Action}s associated with the computer.
*/
@SuppressWarnings("deprecation")
public List<Action> getActions() {
List<Action> result = new ArrayList<Action>();
result.addAll(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
}
@SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
super.getActions().add(a);
}
/**
* This is where the log from the remote agent goes.
* The method also creates a log directory if required.
* @see #getLogDir(), #relocateOldLogs()
*/
public @Nonnull File getLogFile() {
return new File(getLogDir(),"slave.log");
}
/**
* Directory where rotated slave logs are stored.
*
* The method also creates a log directory if required.
*
* @since 1.613
*/
protected @Nonnull File getLogDir() {
File dir = new File(Jenkins.getInstance().getRootDir(),"logs/slaves/"+nodeName);
if (!dir.exists() && !dir.mkdirs()) {
LOGGER.severe("Failed to create slave log directory " + dir.getAbsolutePath());
}
return dir;
}
/**
* Gets the object that coordinates the workspace allocation on this computer.
*/
public WorkspaceList getWorkspaceList() {
return workspaceList;
}
/**
* Gets the string representation of the slave log.
*/
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Used to URL-bind {@link AnnotatedLargeText}.
*/
public AnnotatedLargeText<Computer> getLogText() {
return new AnnotatedLargeText<Computer>(getLogFile(), Charset.defaultCharset(), false, this);
}
public ACL getACL() {
return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause.
*
* @return
* null if the system was put offline without given a cause.
*/
@Exported
public OfflineCause getOfflineCause() {
return offlineCause;
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause as a string (without user info).
*
* @return
* empty string if the system was put offline without given a cause.
*/
@Exported
public String getOfflineCauseReason() {
if (offlineCause == null) {
return "";
}
// fetch the localized string for "Disconnected By"
String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("","");
// regex to remove commented reason base string
String gsub1 = "^" + gsub_base + "[\\w\\W]* \\: ";
// regex to remove non-commented reason base string
String gsub2 = "^" + gsub_base + "[\\w\\W]*";
String newString = offlineCause.toString().replaceAll(gsub1, "");
return newString.replaceAll(gsub2, "");
}
/**
* Gets the channel that can be used to run a program on this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract @Nullable VirtualChannel getChannel();
/**
* Gets the default charset of this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract Charset getDefaultCharset();
/**
* Gets the logs recorded by this slave.
*/
public abstract List<LogRecord> getLogRecords() throws IOException, InterruptedException;
/**
* If {@link #getChannel()}==null, attempts to relaunch the slave agent.
*/
public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
/**
* @deprecated since 2009-01-06. Use {@link #connect(boolean)}
*/
@Deprecated
public final void launch() {
connect(true);
}
/**
* Do the same as {@link #doLaunchSlaveAgent(StaplerRequest, StaplerResponse)}
* but outside the context of serving a request.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
public final Future<?> connect(boolean forceReconnect) {
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
}
/**
* Allows implementing-classes to provide an implementation for the connect method.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
protected abstract Future<?> _connect(boolean forceReconnect);
/**
* CLI command to reconnect this node.
*/
@CLIMethod(name="connect-node")
public void cliConnect(@Option(name="-f",usage="Cancel any currently pending connect operation and retry from scratch") boolean force) throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
connect(force).get();
}
/**
* Gets the time (since epoch) when this computer connected.
*
* @return The time in ms since epoch when this computer last connected.
*/
public final long getConnectTime() {
return connectTime;
}
/**
* Disconnect this computer.
*
* If this is the master, no-op. This method may return immediately
* while the launch operation happens asynchronously.
*
* @param cause
* Object that identifies the reason the node was disconnected.
*
* @return
* {@link Future} to track the asynchronous disconnect operation.
* @see #connect(boolean)
* @since 1.320
*/
public Future<?> disconnect(OfflineCause cause) {
recordTermination();
offlineCause = cause;
if (Util.isOverridden(Computer.class,getClass(),"disconnect"))
return disconnect(); // legacy subtypes that extend disconnect().
connectTime=0;
return Futures.precomputed(null);
}
/**
* Equivalent to {@code disconnect(null)}
*
* @deprecated as of 1.320.
* Use {@link #disconnect(OfflineCause)} and specify the cause.
*/
@Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
connectTime=0;
return Futures.precomputed(null);
}
/**
* CLI command to disconnects this node.
*/
@CLIMethod(name="disconnect-node")
public void cliDisconnect(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
disconnect(new ByCLI(cause)).get();
}
/**
* CLI command to mark the node offline.
*/
@CLIMethod(name="offline-node")
public void cliOffline(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
setTemporarilyOffline(true, new ByCLI(cause));
}
@CLIMethod(name="online-node")
public void cliOnline() throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
setTemporarilyOffline(false, null);
}
/**
* Number of {@link Executor}s that are configured for this computer.
*
* <p>
* When this value is decreased, it is temporarily possible
* for {@link #executors} to have a larger number than this.
*/
// ugly name to let EL access this
@Exported
public int getNumExecutors() {
return numExecutors;
}
/**
* Returns {@link Node#getNodeName() the name of the node}.
*/
public @Nonnull String getName() {
return nodeName != null ? nodeName : "";
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @since 1.624
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public abstract @CheckForNull Boolean isUnix();
/**
* Returns the {@link Node} that this computer represents.
*
* @return
* null if the configuration has changed and the node is removed, yet the corresponding {@link Computer}
* is not yet gone.
*/
public @CheckForNull Node getNode() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return null;
}
if (nodeName == null) {
return j;
}
return j.getNode(nodeName);
}
@Exported
public LoadStatistics getLoadStatistics() {
return LabelAtom.get(nodeName != null ? nodeName : Jenkins.getInstance().getSelfLabel().toString()).loadStatistics;
}
public BuildTimelineWidget getTimeline() {
return new BuildTimelineWidget(getBuilds());
}
/**
* {@inheritDoc}
*/
@Override
public void taskAccepted(Executor executor, Queue.Task task) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
// dummy implementation
}
@Exported
public boolean isOffline() {
return temporarilyOffline || getChannel()==null;
}
public final boolean isOnline() {
return !isOffline();
}
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
@Exported
public boolean isManualLaunchAllowed() {
return getRetentionStrategy().isManualLaunchAllowed(this);
}
/**
* Is a {@link #connect(boolean)} operation in progress?
*/
public abstract boolean isConnecting();
/**
* Returns true if this computer is supposed to be launched via JNLP.
* @deprecated since 2008-05-18.
* See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
*/
@Exported
@Deprecated
public boolean isJnlpAgent() {
return false;
}
/**
* Returns true if this computer can be launched by Hudson proactively and automatically.
*
* <p>
* For example, JNLP slaves return {@code false} from this, because the launch process
* needs to be initiated from the slave side.
*/
@Exported
public boolean isLaunchSupported() {
return true;
}
/**
* Returns true if this node is marked temporarily offline by the user.
*
* <p>
* In contrast, {@link #isOffline()} represents the actual online/offline
* state. For example, this method may return false while {@link #isOffline()}
* returns true if the slave agent failed to launch.
*
* @deprecated
* You should almost always want {@link #isOffline()}.
* This method is marked as deprecated to warn people when they
* accidentally call this method.
*/
@Exported
@Deprecated
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
/**
* @deprecated as of 1.320.
* Use {@link #setTemporarilyOffline(boolean, OfflineCause)}
*/
@Deprecated
public void setTemporarilyOffline(boolean temporarilyOffline) {
setTemporarilyOffline(temporarilyOffline,null);
}
/**
* Marks the computer as temporarily offline. This retains the underlying
* {@link Channel} connection, but prevent builds from executing.
*
* @param cause
* If the first argument is true, specify the reason why the node is being put
* offline.
*/
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) {
offlineCause = temporarilyOffline ? cause : null;
this.temporarilyOffline = temporarilyOffline;
Node node = getNode();
if (node != null) {
node.setTemporaryOfflineCause(offlineCause);
}
synchronized (statusChangeLock) {
statusChangeLock.notifyAll();
}
for (ComputerListener cl : ComputerListener.all()) {
if (temporarilyOffline) cl.onTemporarilyOffline(this,cause);
else cl.onTemporarilyOnline(this);
}
}
@Exported
public String getIcon() {
if(isOffline())
return "computer-x.png";
else
return "computer.png";
}
@Exported
public String getIconClassName() {
if(isOffline())
return "icon-computer-x";
else
return "icon-computer";
}
public String getIconAltText() {
if(isOffline())
return "[offline]";
else
return "[online]";
}
@Exported
@Override public @Nonnull String getDisplayName() {
return nodeName;
}
public String getCaption() {
return Messages.Computer_Caption(nodeName);
}
public String getUrl() {
return "computer/" + Util.rawEncode(getName()) + "/";
}
/**
* Returns projects that are tied on this node.
*/
public List<AbstractProject> getTiedJobs() {
Node node = getNode();
return (node != null) ? node.getSelfLabel().getTiedJobs() : Collections.EMPTY_LIST;
}
public RunList getBuilds() {
return new RunList(Jenkins.getInstance().getAllItems(Job.class)).node(getNode());
}
/**
* Called to notify {@link Computer} that its corresponding {@link Node}
* configuration is updated.
*/
protected void setNode(Node node) {
assert node!=null;
if(node instanceof Slave)
this.nodeName = node.getNodeName();
else
this.nodeName = null;
setNumExecutors(node.getNumExecutors());
if (this.temporarilyOffline) {
// When we get a new node, push our current temp offline
// status to it (as the status is not carried across
// configuration changes that recreate the node).
// Since this is also called the very first time this
// Computer is created, avoid pushing an empty status
// as that could overwrite any status that the Node
// brought along from its persisted config data.
node.setTemporaryOfflineCause(this.offlineCause);
}
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #onRemoved()
*/
protected void kill() {
// On most code paths, this should already be zero, and thus this next call becomes a no-op... and more
// importantly it will not acquire a lock on the Queue... not that the lock is bad, more that the lock
// may delay unnecessarily
setNumExecutors(0);
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* <p>
* Note that the Queue lock is already held when this method is called.
*
* @see #onRemoved()
*/
@Restricted(NoExternalUse.class)
@GuardedBy("hudson.model.Queue.lock")
/*package*/ void inflictMortalWound() {
setNumExecutors(0);
}
/**
* Called by {@link Jenkins} when this computer is removed.
*
* <p>
* This happens when list of nodes are updated (for example by {@link Jenkins#setNodes(List)} and
* the computer becomes redundant. Such {@link Computer}s get {@linkplain #kill() killed}, then
* after all its executors are finished, this method is called.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #kill()
* @since 1.510
*/
protected void onRemoved(){
}
/**
* Calling path, *means protected by Queue.withLock
*
* Computer.doConfigSubmit -> Computer.replaceBy ->Jenkins.setNodes* ->Computer.setNode
* AbstractCIBase.updateComputerList->Computer.inflictMortalWound*
* AbstractCIBase.updateComputerList->AbstractCIBase.updateComputer* ->Computer.setNode
* AbstractCIBase.updateComputerList->AbstractCIBase.killComputer->Computer.kill
* Computer.constructor->Computer.setNode
* Computer.kill is called after numExecutors set to zero(Computer.inflictMortalWound) so not need the Queue.lock
*
* @param number of executors
*/
@GuardedBy("hudson.model.Queue.lock")
private void setNumExecutors(int n) {
this.numExecutors = n;
final int diff = executors.size()-n;
if (diff>0) {
// we have too many executors
// send signal to all idle executors to potentially kill them off
// need the Queue maintenance lock held to prevent concurrent job assignment on the idle executors
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Executor e : executors )
if(e.isIdle())
e.interrupt();
}
});
}
if (diff<0) {
// if the number is increased, add new ones
addNewExecutorIfNecessary();
}
}
private void addNewExecutorIfNecessary() {
Set<Integer> availableNumbers = new HashSet<Integer>();
for (int i = 0; i < numExecutors; i++)
availableNumbers.add(i);
for (Executor executor : executors)
availableNumbers.remove(executor.getNumber());
for (Integer number : availableNumbers) {
/* There may be busy executors with higher index, so only
fill up until numExecutors is reached.
Extra executors will call removeExecutor(...) and that
will create any necessary executors from #0 again. */
if (executors.size() < numExecutors) {
Executor e = new Executor(this, number);
executors.add(e);
}
}
}
/**
* Returns the number of idle {@link Executor}s that can start working immediately.
*/
public int countIdle() {
int n = 0;
for (Executor e : executors) {
if(e.isIdle())
n++;
}
return n;
}
/**
* Returns the number of {@link Executor}s that are doing some work right now.
*/
public final int countBusy() {
return countExecutors()-countIdle();
}
/**
* Returns the current size of the executor pool for this computer.
* This number may temporarily differ from {@link #getNumExecutors()} if there
* are busy tasks when the configured size is decreased. OneOffExecutors are
* not included in this count.
*/
public final int countExecutors() {
return executors.size();
}
/**
* Gets the read-only snapshot view of all {@link Executor}s.
*/
@Exported
public List<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
}
/**
* Gets the read-only snapshot view of all {@link OneOffExecutor}s.
*/
@Exported
public List<OneOffExecutor> getOneOffExecutors() {
return new ArrayList<OneOffExecutor>(oneOffExecutors);
}
/**
* Used to render the list of executors.
* @return a snapshot of the executor display information
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
int index = 0;
for (Executor e: executors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e));
}
index++;
}
index = 0;
for (OneOffExecutor e: oneOffExecutors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e));
}
index++;
}
return result;
}
/**
* Returns true if all the executors of this computer are idle.
*/
@Exported
public final boolean isIdle() {
if (!oneOffExecutors.isEmpty())
return false;
for (Executor e : executors)
if(!e.isIdle())
return false;
return true;
}
/**
* Returns true if this computer has some idle executors that can take more workload.
*/
public final boolean isPartiallyIdle() {
for (Executor e : executors)
if(e.isIdle())
return true;
return false;
}
/**
* Returns the time when this computer last became idle.
*
* <p>
* If this computer is already idle, the return value will point to the
* time in the past since when this computer has been idle.
*
* <p>
* If this computer is busy, the return value will point to the
* time in the future where this computer will be expected to become free.
*/
public final long getIdleStartMilliseconds() {
long firstIdle = Long.MIN_VALUE;
for (Executor e : oneOffExecutors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
for (Executor e : executors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
return firstIdle;
}
/**
* Returns the time when this computer first became in demand.
*/
public final long getDemandStartMilliseconds() {
long firstDemand = Long.MAX_VALUE;
for (Queue.BuildableItem item : Jenkins.getInstance().getQueue().getBuildableItems(this)) {
firstDemand = Math.min(item.buildableStartMilliseconds, firstDemand);
}
return firstDemand;
}
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ void removeExecutor(final Executor e) {
final Runnable task = new Runnable() {
@Override
public void run() {
synchronized (Computer.this) {
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) {
AbstractCIBase ciBase = Jenkins.getInstance();
if (ciBase != null) {
ciBase.removeComputer(Computer.this);
}
}
}
}
};
if (!Queue.tryWithLock(task)) {
// JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks
threadPoolForRemoting.submit(Queue.wrapWithLock(task));
}
}
/**
* Returns true if any of the executors are {@linkplain Executor#isActive active}.
*
* Note that if an executor dies, we'll leave it in {@link #executors} until
* the administrator yanks it out, so that we can see why it died.
*
* @since 1.509
*/
protected boolean isAlive() {
for (Executor e : executors)
if (e.isActive())
return true;
return false;
}
/**
* Interrupt all {@link Executor}s.
* Called from {@link Jenkins#cleanUp}.
*/
public void interrupt() {
Queue.withLock(new Runnable() {
@Override
public void run() {
for (Executor e : executors) {
e.interruptForShutdown();
}
}
});
}
public String getSearchUrl() {
return getUrl();
}
/**
* {@link RetentionStrategy} associated with this computer.
*
* @return
* never null. This method return {@code RetentionStrategy<? super T>} where
* {@code T=this.getClass()}.
*/
public abstract RetentionStrategy getRetentionStrategy();
/**
* Expose monitoring data for the remote API.
*/
@Exported(inline=true)
public Map<String/*monitor name*/,Object> getMonitorData() {
Map<String,Object> r = new HashMap<String, Object>();
for (NodeMonitor monitor : NodeMonitor.getAll())
r.put(monitor.getClass().getName(),monitor.data(this));
return r;
}
/**
* Gets the system properties of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<Object,Object> getSystemProperties() throws IOException, InterruptedException {
return RemotingDiagnostics.getSystemProperties(getChannel());
}
/**
* @deprecated as of 1.292
* Use {@link #getEnvironment()} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
return getEnvironment();
}
/**
* Returns cached environment variables (copy to prevent modification) for the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars cachedEnvironment = this.cachedEnvironment;
if (cachedEnvironment != null) {
return new EnvVars(cachedEnvironment);
}
cachedEnvironment = EnvVars.getRemote(getChannel());
this.cachedEnvironment = cachedEnvironment;
return new EnvVars(cachedEnvironment);
}
/**
* Creates an environment variable override to be used for launching processes on this node.
*
* @see ProcStarter#envs(Map)
* @since 1.489
*/
public @Nonnull EnvVars buildEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException {
EnvVars env = new EnvVars();
Node node = getNode();
if (node==null) return env; // bail out
for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
for (NodeProperty nodeProperty: node.getNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
// TODO: hmm, they don't really belong
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl!=null) {
env.put("HUDSON_URL", rootUrl); // Legacy.
env.put("JENKINS_URL", rootUrl);
}
return env;
}
/**
* Gets the thread dump of the slave JVM.
* @return
* key is the thread name, and the value is the pre-formatted dump.
*/
public Map<String,String> getThreadDump() throws IOException, InterruptedException {
return RemotingDiagnostics.getThreadDump(getChannel());
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,getChannel());
}
/**
* This method tries to compute the name of the host that's reachable by all the other nodes.
*
* <p>
* Since it's possible that the slave is not reachable from the master (it may be behind a firewall,
* connecting to master via JNLP), this method may return null.
*
* It's surprisingly tricky for a machine to know a name that other systems can get to,
* especially between things like DNS search suffix, the hosts file, and YP.
*
* <p>
* So the technique here is to compute possible interfaces and names on the slave,
* then try to ping them from the master, and pick the one that worked.
*
* <p>
* The computation may take some time, so it employs caching to make the successive lookups faster.
*
* @since 1.300
* @return
* null if the host name cannot be computed (for example because this computer is offline,
* because the slave is behind the firewall, etc.)
*/
public String getHostName() throws IOException, InterruptedException {
if(hostNameCached)
// in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful.
return cachedHostName;
VirtualChannel channel = getChannel();
if(channel==null) return null; // can't compute right now
for( String address : channel.call(new ListPossibleNames())) {
try {
InetAddress ia = InetAddress.getByName(address);
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
continue;
}
if(!ComputerPinger.checkIsReachable(ia, 3)) {
LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
continue;
}
cachedHostName = ia.getCanonicalHostName();
hostNameCached = true;
return cachedHostName;
} catch (IOException e) {
// if a given name fails to parse on this host, we get this error
LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
lr.setThrown(e);
lr.setParameters(new Object[]{address});
LOGGER.log(lr);
}
}
// allow the administrator to manually specify the host name as a fallback. HUDSON-5373
cachedHostName = channel.call(new GetFallbackName());
hostNameCached = true;
return cachedHostName;
}
/**
* Starts executing a fly-weight task.
*/
/*package*/ final void startFlyWeightTask(WorkUnit p) {
OneOffExecutor e = new OneOffExecutor(this);
e.start(p);
oneOffExecutors.add(e);
}
/*package*/ final void remove(OneOffExecutor e) {
oneOffExecutors.remove(e);
}
private static class ListPossibleNames extends MasterToSlaveCallable<List<String>,IOException> {
/**
* In the normal case we would use {@link Computer} as the logger's name, however to
* do that we would have to send the {@link Computer} class over to the remote classloader
* and then it would need to be loaded, which pulls in {@link Jenkins} and loads that
* and then that fails to load as you are not supposed to do that. Another option
* would be to export the logger over remoting, with increased complexity as a result.
* Instead we just use a loger based on this class name and prevent any references to
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<String>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName());
Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
InetAddress ia = e.nextElement();
if(ia.isLoopbackAddress()) {
LOGGER.log(Level.FINE, "{0} is a loopback address", ia);
continue;
}
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia);
continue;
}
LOGGER.log(Level.FINE, "{0} is a viable candidate", ia);
names.add(ia.getHostAddress());
}
}
return names;
}
private static final long serialVersionUID = 1L;
}
private static class GetFallbackName extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
return System.getProperty("host.name");
}
private static final long serialVersionUID = 1L;
}
public static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "Computer.threadPoolForRemoting"))));
//
//
// UI
//
//
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds());
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", getBuilds().failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName() + suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp);
}
@RequirePOST
public HttpResponse doToggleOffline(@QueryParameter String offlineMessage) throws IOException, ServletException {
if(!temporarilyOffline) {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(!temporarilyOffline,
new OfflineCause.UserCause(User.current(), offlineMessage));
} else {
checkPermission(CONNECT);
setTemporarilyOffline(!temporarilyOffline,null);
}
return HttpResponses.redirectToDot();
}
@RequirePOST
public HttpResponse doChangeOfflineCause(@QueryParameter String offlineMessage) throws IOException, ServletException {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(true,
new OfflineCause.UserCause(User.current(), offlineMessage));
return HttpResponses.redirectToDot();
}
public Api getApi() {
return new Api(this);
}
/**
* Dumps the contents of the export table.
*/
public void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
// this is a debug probe and may expose sensitive information
checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("text/plain");
PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req));
VirtualChannel vc = getChannel();
if (vc instanceof Channel) {
w.println("Master to slave");
((Channel)vc).dumpExportTable(w);
w.flush(); // flush here once so that even if the dump from the slave fails, the client gets some useful info
w.println("\n\n\nSlave to master");
w.print(vc.call(new DumpExportTableTask()));
} else {
w.println(Messages.Computer_BadChannel());
}
w.close();
}
private static final class DumpExportTableTask extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Channel.current().dumpExportTable(pw);
pw.close();
return sw.toString();
}
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_script.jelly");
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_scriptText.jelly");
}
protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
/**
* Accepts the update to the node configuration.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(CONFIGURE);
String name = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name"));
Jenkins.checkGoodName(name);
Node node = getNode();
if (node == null) {
throw new ServletException("No such node " + nodeName);
}
Node result = node.reconfigure(req, req.getSubmittedForm());
replaceBy(result);
// take the user back to the slave top page.
rsp.sendRedirect2("../" + result.getNodeName() + '/');
}
/**
* Accepts <tt>config.xml</tt> submission, as well as serve it.
*/
@WebMethod(name = "config.xml")
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
if (req.getMethod().equals("GET")) {
// read
checkPermission(EXTENDED_READ);
rsp.setContentType("application/xml");
Node node = getNode();
if (node == null) {
throw HttpResponses.notFound();
}
Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream());
return;
}
if (req.getMethod().equals("POST")) {
// submission
updateByXml(req.getInputStream());
return;
}
// huh?
rsp.sendError(SC_BAD_REQUEST);
}
/**
* Replaces the current {@link Node} by another one.
*/
private void replaceBy(final Node newNode) throws ServletException, IOException {
final Jenkins app = Jenkins.getInstance();
// use the queue lock until Nodes has a way of directly modifying a single node.
Queue.withLock(new NotReallyRoleSensitiveCallable<Void, IOException>() {
public Void call() throws IOException {
List<Node> nodes = new ArrayList<Node>(app.getNodes());
Node node = getNode();
int i = (node != null) ? nodes.indexOf(node) : -1;
if(i<0) {
throw new IOException("This slave appears to be removed while you were editing the configuration");
}
nodes.set(i, newNode);
app.setNodes(nodes);
return null;
}
});
}
/**
* Updates Job by its XML definition.
*
* @since 1.526
*/
public void updateByXml(final InputStream source) throws IOException, ServletException {
checkPermission(CONFIGURE);
Node result = (Node)Jenkins.XSTREAM2.fromXML(source);
replaceBy(result);
}
/**
* Really deletes the slave.
*/
@RequirePOST
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
Node node = getNode();
if (node != null) {
Jenkins.getInstance().removeNode(node);
} else {
AbstractCIBase app = Jenkins.getInstance();
app.removeComputer(this);
}
return new HttpRedirect("..");
}
/**
* Blocks until the node becomes online/offline.
*/
@CLIMethod(name="wait-node-online")
public void waitUntilOnline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOnline())
statusChangeLock.wait(1000);
}
}
@CLIMethod(name="wait-node-offline")
public void waitUntilOffline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOffline())
statusChangeLock.wait(1000);
}
}
/**
* Handles incremental log.
*/
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req, rsp);
}
/**
* Gets the current {@link Computer} that the build is running.
* This method only works when called during a build, such as by
* {@link hudson.tasks.Publisher}, {@link hudson.tasks.BuildWrapper}, etc.
* @return the {@link Computer} associated with {@link Executor#currentExecutor}, or (consistently as of 1.591) null if not on an executor thread
*/
public static @Nullable Computer currentComputer() {
Executor e = Executor.currentExecutor();
return e != null ? e.getOwner() : null;
}
/**
* Returns {@code true} if the computer is accepting tasks. Needed to allow slaves programmatic suspension of task
* scheduling that does not overlap with being offline.
*
* @return {@code true} if the computer is accepting tasks
* @see hudson.slaves.RetentionStrategy#isAcceptingTasks(Computer)
* @see hudson.model.Node#isAcceptingTasks()
*/
@OverrideMustInvoke(When.ANYTIME)
public boolean isAcceptingTasks() {
final Node node = getNode();
return getRetentionStrategy().isAcceptingTasks(this) && (node == null || node.isAcceptingTasks());
}
/**
* Used for CLI binding.
*/
@CLIResolver
public static Computer resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Slave name, or empty string for master") String name) throws CmdLineException {
Jenkins h = Jenkins.getInstance();
Computer item = h.getComputer(name);
if (item==null) {
List<String> names = new ArrayList<String>();
for (Computer c : h.getComputers())
if (c.getName().length()>0)
names.add(c.getName());
throw new CmdLineException(null,Messages.Computer_NoSuchSlaveExists(name,EditDistance.findNearest(name,names)));
}
return item;
}
/**
* Relocate log files in the old location to the new location.
*
* Files were used to be $JENKINS_ROOT/slave-NAME.log (and .1, .2, ...)
* but now they are at $JENKINS_ROOT/logs/slaves/NAME/slave.log (and .1, .2, ...)
*
* @see #getLogFile()
*/
@Initializer
public static void relocateOldLogs() {
relocateOldLogs(Jenkins.getInstance().getRootDir());
}
/*package*/ static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessful=f.renameTo(newLocation);
if (relocationSuccessful) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
/**
* A value class to provide a consistent snapshot view of the state of an executor to avoid race conditions
* during rendering of the executors list.
*
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public static class DisplayExecutor implements ModelObject {
@Nonnull
private final String displayName;
@Nonnull
private final String url;
@Nonnull
private final Executor executor;
public DisplayExecutor(@Nonnull String displayName, @Nonnull String url, @Nonnull Executor executor) {
this.displayName = displayName;
this.url = url;
this.executor = executor;
}
@Override
@Nonnull
public String getDisplayName() {
return displayName;
}
@Nonnull
public String getUrl() {
return url;
}
@Nonnull
public Executor getExecutor() {
return executor;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DisplayExecutor that = (DisplayExecutor) o;
if (!executor.equals(that.executor)) {
return false;
}
return true;
}
@Extension(ordinal = Double.MAX_VALUE)
@Restricted(DoNotUse.class)
public static class InternalComputerListener extends ComputerListener {
@Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
c.cachedEnvironment = null;
}
}
@Override
public int hashCode() {
return executor.hashCode();
}
}
/**
* Used to trace requests to terminate a computer.
*
* @since 1.607
*/
public static class TerminationRequest extends RuntimeException {
private final long when;
public TerminationRequest(String message) {
super(message);
this.when = System.currentTimeMillis();
}
/**
* Returns the when the termination request was created.
*
* @return the difference, measured in milliseconds, between
* the time of the termination request and midnight, January 1, 1970 UTC.
*/
public long getWhen() {
return when;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title());
public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._Computer_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.COMPUTER);
/**
* @since 1.532
*/
public static final Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._Computer_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.COMPUTER});
public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._Computer_DeletePermission_Description(), Permission.DELETE, PermissionScope.COMPUTER);
public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._Computer_CreatePermission_Description(), Permission.CREATE, PermissionScope.COMPUTER);
public static final Permission DISCONNECT = new Permission(PERMISSIONS,"Disconnect", Messages._Computer_DisconnectPermission_Description(), Jenkins.ADMINISTER, PermissionScope.COMPUTER);
public static final Permission CONNECT = new Permission(PERMISSIONS,"Connect", Messages._Computer_ConnectPermission_Description(), DISCONNECT, PermissionScope.COMPUTER);
public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._Computer_BuildPermission_Description(), Permission.WRITE, PermissionScope.COMPUTER);
private static final Logger LOGGER = Logger.getLogger(Computer.class.getName());
}
| core/src/main/java/hudson/model/Computer.java | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Red Hat, Inc., Seiji Sogabe, Stephen Connolly, Thomas J. Black, Tom Huybrechts, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;
import edu.umd.cs.findbugs.annotations.When;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher.ProcStarter;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.console.AnnotatedLargeText;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.FlyweightTask;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.WorkUnit;
import hudson.node_monitors.NodeMonitor;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.WorkspaceList;
import hudson.slaves.OfflineCause;
import hudson.slaves.OfflineCause.ByCLI;
import hudson.util.DaemonThreadFactory;
import hudson.util.EditDistance;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.RunList;
import hudson.util.Futures;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.security.MasterToSlaveCallable;
import jenkins.security.NotReallyRoleSensitiveCallable;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Represents the running state of a remote computer that holds {@link Executor}s.
*
* <p>
* {@link Executor}s on one {@link Computer} are transparently interchangeable
* (that is the definition of {@link Computer}).
*
* <p>
* This object is related to {@link Node} but they have some significant differences.
* {@link Computer} primarily works as a holder of {@link Executor}s, so
* if a {@link Node} is configured (probably temporarily) with 0 executors,
* you won't have a {@link Computer} object for it (except for the master node,
* which always gets its {@link Computer} in case we have no static executors and
* we need to run a {@link FlyweightTask} - see JENKINS-7291 for more discussion.)
*
* Also, even if you remove a {@link Node}, it takes time for the corresponding
* {@link Computer} to be removed, if some builds are already in progress on that
* node. Or when the node configuration is changed, unaffected {@link Computer} object
* remains intact, while all the {@link Node} objects will go away.
*
* <p>
* This object also serves UI (unlike {@link Node}), and can be used along with
* {@link TransientComputerActionFactory} to add {@link Action}s to {@link Computer}s.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public /*transient*/ abstract class Computer extends Actionable implements AccessControlled, ExecutorListener {
private final CopyOnWriteArrayList<Executor> executors = new CopyOnWriteArrayList<Executor>();
// TODO:
private final CopyOnWriteArrayList<OneOffExecutor> oneOffExecutors = new CopyOnWriteArrayList<OneOffExecutor>();
private int numExecutors;
/**
* Contains info about reason behind computer being offline.
*/
protected volatile OfflineCause offlineCause;
private long connectTime = 0;
/**
* True if Jenkins shouldn't start new builds on this node.
*/
private boolean temporarilyOffline;
/**
* {@link Node} object may be created and deleted independently
* from this object.
*/
protected String nodeName;
/**
* @see #getHostName()
*/
private volatile String cachedHostName;
private volatile boolean hostNameCached;
/**
* @see #getEnvironment()
*/
private volatile EnvVars cachedEnvironment;
private final WorkspaceList workspaceList = new WorkspaceList();
protected transient List<Action> transientActions;
protected final Object statusChangeLock = new Object();
/**
* Keeps track of stack traces to track the tremination requests for this computer.
*
* @since 1.607
* @see Executor#resetWorkUnit(String)
*/
private transient final List<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
/**
* This method captures the information of a request to terminate a computer instance. Method is public as
* it needs to be called from {@link AbstractCloudSlave} and {@link jenkins.model.Nodes}. In general you should
* not need to call this method directly, however if implementing a custom node type or a different path
* for removing nodes, it may make sense to call this method in order to capture the originating request.
*
* @since 1.607
*/
public void recordTermination() {
StaplerRequest request = Stapler.getCurrentRequest();
if (request != null) {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId(),
request.getRequestURL()
)
));
} else {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d]",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId()
)
));
}
}
/**
* Returns the list of captured termination requests for this Computer. This method is used by {@link Executor}
* to provide details on why a Computer was removed in-between work being scheduled against the {@link Executor}
* and the {@link Executor} starting to execute the task.
*
* @return the (possibly empty) list of termination requests.
* @see Executor#resetWorkUnit(String)
* @since 1.607
*/
public List<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(terminatedBy);
}
public Computer(Node node) {
setNode(node);
}
/**
* Returns list of all boxes {@link ComputerPanelBox}s.
*/
public List<ComputerPanelBox> getComputerPanelBoxs(){
return ComputerPanelBox.all(this);
}
/**
* Returns the transient {@link Action}s associated with the computer.
*/
@SuppressWarnings("deprecation")
public List<Action> getActions() {
List<Action> result = new ArrayList<Action>();
result.addAll(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
}
@SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
super.getActions().add(a);
}
/**
* This is where the log from the remote agent goes.
* The method also creates a log directory if required.
* @see #getLogDir(), #relocateOldLogs()
*/
public @Nonnull File getLogFile() {
return new File(getLogDir(),"slave.log");
}
/**
* Directory where rotated slave logs are stored.
*
* The method also creates a log directory if required.
*
* @since 1.613
*/
protected @Nonnull File getLogDir() {
File dir = new File(Jenkins.getInstance().getRootDir(),"logs/slaves/"+nodeName);
if (!dir.exists() && !dir.mkdirs()) {
LOGGER.severe("Failed to create slave log directory " + dir.getAbsolutePath());
}
return dir;
}
/**
* Gets the object that coordinates the workspace allocation on this computer.
*/
public WorkspaceList getWorkspaceList() {
return workspaceList;
}
/**
* Gets the string representation of the slave log.
*/
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Used to URL-bind {@link AnnotatedLargeText}.
*/
public AnnotatedLargeText<Computer> getLogText() {
return new AnnotatedLargeText<Computer>(getLogFile(), Charset.defaultCharset(), false, this);
}
public ACL getACL() {
return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause.
*
* @return
* null if the system was put offline without given a cause.
*/
@Exported
public OfflineCause getOfflineCause() {
return offlineCause;
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause as a string (without user info).
*
* @return
* empty string if the system was put offline without given a cause.
*/
@Exported
public String getOfflineCauseReason() {
if (offlineCause == null) {
return "";
}
// fetch the localized string for "Disconnected By"
String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("","");
// regex to remove commented reason base string
String gsub1 = "^" + gsub_base + "[\\w\\W]* \\: ";
// regex to remove non-commented reason base string
String gsub2 = "^" + gsub_base + "[\\w\\W]*";
String newString = offlineCause.toString().replaceAll(gsub1, "");
return newString.replaceAll(gsub2, "");
}
/**
* Gets the channel that can be used to run a program on this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract @Nullable VirtualChannel getChannel();
/**
* Gets the default charset of this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract Charset getDefaultCharset();
/**
* Gets the logs recorded by this slave.
*/
public abstract List<LogRecord> getLogRecords() throws IOException, InterruptedException;
/**
* If {@link #getChannel()}==null, attempts to relaunch the slave agent.
*/
public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
/**
* @deprecated since 2009-01-06. Use {@link #connect(boolean)}
*/
@Deprecated
public final void launch() {
connect(true);
}
/**
* Do the same as {@link #doLaunchSlaveAgent(StaplerRequest, StaplerResponse)}
* but outside the context of serving a request.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
public final Future<?> connect(boolean forceReconnect) {
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
}
/**
* Allows implementing-classes to provide an implementation for the connect method.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
protected abstract Future<?> _connect(boolean forceReconnect);
/**
* CLI command to reconnect this node.
*/
@CLIMethod(name="connect-node")
public void cliConnect(@Option(name="-f",usage="Cancel any currently pending connect operation and retry from scratch") boolean force) throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
connect(force).get();
}
/**
* Gets the time (since epoch) when this computer connected.
*
* @return The time in ms since epoch when this computer last connected.
*/
public final long getConnectTime() {
return connectTime;
}
/**
* Disconnect this computer.
*
* If this is the master, no-op. This method may return immediately
* while the launch operation happens asynchronously.
*
* @param cause
* Object that identifies the reason the node was disconnected.
*
* @return
* {@link Future} to track the asynchronous disconnect operation.
* @see #connect(boolean)
* @since 1.320
*/
public Future<?> disconnect(OfflineCause cause) {
recordTermination();
offlineCause = cause;
if (Util.isOverridden(Computer.class,getClass(),"disconnect"))
return disconnect(); // legacy subtypes that extend disconnect().
connectTime=0;
return Futures.precomputed(null);
}
/**
* Equivalent to {@code disconnect(null)}
*
* @deprecated as of 1.320.
* Use {@link #disconnect(OfflineCause)} and specify the cause.
*/
@Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
connectTime=0;
return Futures.precomputed(null);
}
/**
* CLI command to disconnects this node.
*/
@CLIMethod(name="disconnect-node")
public void cliDisconnect(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
disconnect(new ByCLI(cause)).get();
}
/**
* CLI command to mark the node offline.
*/
@CLIMethod(name="offline-node")
public void cliOffline(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
setTemporarilyOffline(true, new ByCLI(cause));
}
@CLIMethod(name="online-node")
public void cliOnline() throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
setTemporarilyOffline(false, null);
}
/**
* Number of {@link Executor}s that are configured for this computer.
*
* <p>
* When this value is decreased, it is temporarily possible
* for {@link #executors} to have a larger number than this.
*/
// ugly name to let EL access this
@Exported
public int getNumExecutors() {
return numExecutors;
}
/**
* Returns {@link Node#getNodeName() the name of the node}.
*/
public @Nonnull String getName() {
return nodeName != null ? nodeName : "";
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @since 1.624
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public abstract @CheckForNull Boolean isUnix();
/**
* Returns the {@link Node} that this computer represents.
*
* @return
* null if the configuration has changed and the node is removed, yet the corresponding {@link Computer}
* is not yet gone.
*/
public @CheckForNull Node getNode() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return null;
}
if (nodeName == null) {
return j;
}
return j.getNode(nodeName);
}
@Exported
public LoadStatistics getLoadStatistics() {
return LabelAtom.get(nodeName != null ? nodeName : Jenkins.getInstance().getSelfLabel().toString()).loadStatistics;
}
public BuildTimelineWidget getTimeline() {
return new BuildTimelineWidget(getBuilds());
}
/**
* {@inheritDoc}
*/
@Override
public void taskAccepted(Executor executor, Queue.Task task) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
// dummy implementation
}
@Exported
public boolean isOffline() {
return temporarilyOffline || getChannel()==null;
}
public final boolean isOnline() {
return !isOffline();
}
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
@Exported
public boolean isManualLaunchAllowed() {
return getRetentionStrategy().isManualLaunchAllowed(this);
}
/**
* Is a {@link #connect(boolean)} operation in progress?
*/
public abstract boolean isConnecting();
/**
* Returns true if this computer is supposed to be launched via JNLP.
* @deprecated since 2008-05-18.
* See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
*/
@Exported
@Deprecated
public boolean isJnlpAgent() {
return false;
}
/**
* Returns true if this computer can be launched by Hudson proactively and automatically.
*
* <p>
* For example, JNLP slaves return {@code false} from this, because the launch process
* needs to be initiated from the slave side.
*/
@Exported
public boolean isLaunchSupported() {
return true;
}
/**
* Returns true if this node is marked temporarily offline by the user.
*
* <p>
* In contrast, {@link #isOffline()} represents the actual online/offline
* state. For example, this method may return false while {@link #isOffline()}
* returns true if the slave agent failed to launch.
*
* @deprecated
* You should almost always want {@link #isOffline()}.
* This method is marked as deprecated to warn people when they
* accidentally call this method.
*/
@Exported
@Deprecated
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
/**
* @deprecated as of 1.320.
* Use {@link #setTemporarilyOffline(boolean, OfflineCause)}
*/
@Deprecated
public void setTemporarilyOffline(boolean temporarilyOffline) {
setTemporarilyOffline(temporarilyOffline,null);
}
/**
* Marks the computer as temporarily offline. This retains the underlying
* {@link Channel} connection, but prevent builds from executing.
*
* @param cause
* If the first argument is true, specify the reason why the node is being put
* offline.
*/
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) {
offlineCause = temporarilyOffline ? cause : null;
this.temporarilyOffline = temporarilyOffline;
Node node = getNode();
if (node != null) {
node.setTemporaryOfflineCause(offlineCause);
}
synchronized (statusChangeLock) {
statusChangeLock.notifyAll();
}
for (ComputerListener cl : ComputerListener.all()) {
if (temporarilyOffline) cl.onTemporarilyOffline(this,cause);
else cl.onTemporarilyOnline(this);
}
}
@Exported
public String getIcon() {
if(isOffline())
return "computer-x.png";
else
return "computer.png";
}
@Exported
public String getIconClassName() {
if(isOffline())
return "icon-computer-x";
else
return "icon-computer";
}
public String getIconAltText() {
if(isOffline())
return "[offline]";
else
return "[online]";
}
@Exported
@Override public @Nonnull String getDisplayName() {
return nodeName;
}
public String getCaption() {
return Messages.Computer_Caption(nodeName);
}
public String getUrl() {
return "computer/" + Util.rawEncode(getName()) + "/";
}
/**
* Returns projects that are tied on this node.
*/
public List<AbstractProject> getTiedJobs() {
Node node = getNode();
return (node != null) ? node.getSelfLabel().getTiedJobs() : Collections.EMPTY_LIST;
}
public RunList getBuilds() {
return new RunList(Jenkins.getInstance().getAllItems(Job.class)).node(getNode());
}
/**
* Called to notify {@link Computer} that its corresponding {@link Node}
* configuration is updated.
*/
protected void setNode(Node node) {
assert node!=null;
if(node instanceof Slave)
this.nodeName = node.getNodeName();
else
this.nodeName = null;
setNumExecutors(node.getNumExecutors());
if (this.temporarilyOffline) {
// When we get a new node, push our current temp offline
// status to it (as the status is not carried across
// configuration changes that recreate the node).
// Since this is also called the very first time this
// Computer is created, avoid pushing an empty status
// as that could overwrite any status that the Node
// brought along from its persisted config data.
node.setTemporaryOfflineCause(this.offlineCause);
}
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #onRemoved()
*/
protected void kill() {
// On most code paths, this should already be zero, and thus this next call becomes a no-op... and more
// importantly it will not acquire a lock on the Queue... not that the lock is bad, more that the lock
// may delay unnecessarily
setNumExecutors(0);
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* <p>
* Note that the Queue lock is already held when this method is called.
*
* @see #onRemoved()
*/
@Restricted(NoExternalUse.class)
@GuardedBy("hudson.model.Queue.lock")
/*package*/ void inflictMortalWound() {
setNumExecutors(0);
}
/**
* Called by {@link Jenkins} when this computer is removed.
*
* <p>
* This happens when list of nodes are updated (for example by {@link Jenkins#setNodes(List)} and
* the computer becomes redundant. Such {@link Computer}s get {@linkplain #kill() killed}, then
* after all its executors are finished, this method is called.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #kill()
* @since 1.510
*/
protected void onRemoved(){
}
/**
* Calling path, *means protected by Queue.withLock
*
* Computer.doConfigSubmit -> Computer.replaceBy ->Jenkins.setNodes* ->Computer.setNode
* AbstractCIBase.updateComputerList->Computer.inflictMortalWound*
* AbstractCIBase.updateComputerList->AbstractCIBase.updateComputer* ->Computer.setNode
* AbstractCIBase.updateComputerList->AbstractCIBase.killComputer->Computer.kill
* Computer.constructor->Computer.setNode
* Computer.kill is called after numExecutors set to zero(Computer.inflictMortalWound) so not need the Queue.lock
*
* @param number of executors
*/
private void setNumExecutors(int n) {
this.numExecutors = n;
final int diff = executors.size()-n;
if (diff>0) {
// we have too many executors
// send signal to all idle executors to potentially kill them off
// need the Queue maintenance lock held to prevent concurrent job assignment on the idle executors
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Executor e : executors )
if(e.isIdle())
e.interrupt();
}
});
}
if (diff<0) {
// if the number is increased, add new ones
addNewExecutorIfNecessary();
}
}
private void addNewExecutorIfNecessary() {
Set<Integer> availableNumbers = new HashSet<Integer>();
for (int i = 0; i < numExecutors; i++)
availableNumbers.add(i);
for (Executor executor : executors)
availableNumbers.remove(executor.getNumber());
for (Integer number : availableNumbers) {
/* There may be busy executors with higher index, so only
fill up until numExecutors is reached.
Extra executors will call removeExecutor(...) and that
will create any necessary executors from #0 again. */
if (executors.size() < numExecutors) {
Executor e = new Executor(this, number);
executors.add(e);
}
}
}
/**
* Returns the number of idle {@link Executor}s that can start working immediately.
*/
public int countIdle() {
int n = 0;
for (Executor e : executors) {
if(e.isIdle())
n++;
}
return n;
}
/**
* Returns the number of {@link Executor}s that are doing some work right now.
*/
public final int countBusy() {
return countExecutors()-countIdle();
}
/**
* Returns the current size of the executor pool for this computer.
* This number may temporarily differ from {@link #getNumExecutors()} if there
* are busy tasks when the configured size is decreased. OneOffExecutors are
* not included in this count.
*/
public final int countExecutors() {
return executors.size();
}
/**
* Gets the read-only snapshot view of all {@link Executor}s.
*/
@Exported
public List<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
}
/**
* Gets the read-only snapshot view of all {@link OneOffExecutor}s.
*/
@Exported
public List<OneOffExecutor> getOneOffExecutors() {
return new ArrayList<OneOffExecutor>(oneOffExecutors);
}
/**
* Used to render the list of executors.
* @return a snapshot of the executor display information
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
int index = 0;
for (Executor e: executors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e));
}
index++;
}
index = 0;
for (OneOffExecutor e: oneOffExecutors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e));
}
index++;
}
return result;
}
/**
* Returns true if all the executors of this computer are idle.
*/
@Exported
public final boolean isIdle() {
if (!oneOffExecutors.isEmpty())
return false;
for (Executor e : executors)
if(!e.isIdle())
return false;
return true;
}
/**
* Returns true if this computer has some idle executors that can take more workload.
*/
public final boolean isPartiallyIdle() {
for (Executor e : executors)
if(e.isIdle())
return true;
return false;
}
/**
* Returns the time when this computer last became idle.
*
* <p>
* If this computer is already idle, the return value will point to the
* time in the past since when this computer has been idle.
*
* <p>
* If this computer is busy, the return value will point to the
* time in the future where this computer will be expected to become free.
*/
public final long getIdleStartMilliseconds() {
long firstIdle = Long.MIN_VALUE;
for (Executor e : oneOffExecutors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
for (Executor e : executors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
return firstIdle;
}
/**
* Returns the time when this computer first became in demand.
*/
public final long getDemandStartMilliseconds() {
long firstDemand = Long.MAX_VALUE;
for (Queue.BuildableItem item : Jenkins.getInstance().getQueue().getBuildableItems(this)) {
firstDemand = Math.min(item.buildableStartMilliseconds, firstDemand);
}
return firstDemand;
}
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ void removeExecutor(final Executor e) {
final Runnable task = new Runnable() {
@Override
public void run() {
synchronized (Computer.this) {
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) {
AbstractCIBase ciBase = Jenkins.getInstance();
if (ciBase != null) {
ciBase.removeComputer(Computer.this);
}
}
}
}
};
if (!Queue.tryWithLock(task)) {
// JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks
threadPoolForRemoting.submit(Queue.wrapWithLock(task));
}
}
/**
* Returns true if any of the executors are {@linkplain Executor#isActive active}.
*
* Note that if an executor dies, we'll leave it in {@link #executors} until
* the administrator yanks it out, so that we can see why it died.
*
* @since 1.509
*/
protected boolean isAlive() {
for (Executor e : executors)
if (e.isActive())
return true;
return false;
}
/**
* Interrupt all {@link Executor}s.
* Called from {@link Jenkins#cleanUp}.
*/
public void interrupt() {
Queue.withLock(new Runnable() {
@Override
public void run() {
for (Executor e : executors) {
e.interruptForShutdown();
}
}
});
}
public String getSearchUrl() {
return getUrl();
}
/**
* {@link RetentionStrategy} associated with this computer.
*
* @return
* never null. This method return {@code RetentionStrategy<? super T>} where
* {@code T=this.getClass()}.
*/
public abstract RetentionStrategy getRetentionStrategy();
/**
* Expose monitoring data for the remote API.
*/
@Exported(inline=true)
public Map<String/*monitor name*/,Object> getMonitorData() {
Map<String,Object> r = new HashMap<String, Object>();
for (NodeMonitor monitor : NodeMonitor.getAll())
r.put(monitor.getClass().getName(),monitor.data(this));
return r;
}
/**
* Gets the system properties of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<Object,Object> getSystemProperties() throws IOException, InterruptedException {
return RemotingDiagnostics.getSystemProperties(getChannel());
}
/**
* @deprecated as of 1.292
* Use {@link #getEnvironment()} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
return getEnvironment();
}
/**
* Returns cached environment variables (copy to prevent modification) for the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars cachedEnvironment = this.cachedEnvironment;
if (cachedEnvironment != null) {
return new EnvVars(cachedEnvironment);
}
cachedEnvironment = EnvVars.getRemote(getChannel());
this.cachedEnvironment = cachedEnvironment;
return new EnvVars(cachedEnvironment);
}
/**
* Creates an environment variable override to be used for launching processes on this node.
*
* @see ProcStarter#envs(Map)
* @since 1.489
*/
public @Nonnull EnvVars buildEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException {
EnvVars env = new EnvVars();
Node node = getNode();
if (node==null) return env; // bail out
for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
for (NodeProperty nodeProperty: node.getNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
// TODO: hmm, they don't really belong
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl!=null) {
env.put("HUDSON_URL", rootUrl); // Legacy.
env.put("JENKINS_URL", rootUrl);
}
return env;
}
/**
* Gets the thread dump of the slave JVM.
* @return
* key is the thread name, and the value is the pre-formatted dump.
*/
public Map<String,String> getThreadDump() throws IOException, InterruptedException {
return RemotingDiagnostics.getThreadDump(getChannel());
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,getChannel());
}
/**
* This method tries to compute the name of the host that's reachable by all the other nodes.
*
* <p>
* Since it's possible that the slave is not reachable from the master (it may be behind a firewall,
* connecting to master via JNLP), this method may return null.
*
* It's surprisingly tricky for a machine to know a name that other systems can get to,
* especially between things like DNS search suffix, the hosts file, and YP.
*
* <p>
* So the technique here is to compute possible interfaces and names on the slave,
* then try to ping them from the master, and pick the one that worked.
*
* <p>
* The computation may take some time, so it employs caching to make the successive lookups faster.
*
* @since 1.300
* @return
* null if the host name cannot be computed (for example because this computer is offline,
* because the slave is behind the firewall, etc.)
*/
public String getHostName() throws IOException, InterruptedException {
if(hostNameCached)
// in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful.
return cachedHostName;
VirtualChannel channel = getChannel();
if(channel==null) return null; // can't compute right now
for( String address : channel.call(new ListPossibleNames())) {
try {
InetAddress ia = InetAddress.getByName(address);
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
continue;
}
if(!ComputerPinger.checkIsReachable(ia, 3)) {
LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
continue;
}
cachedHostName = ia.getCanonicalHostName();
hostNameCached = true;
return cachedHostName;
} catch (IOException e) {
// if a given name fails to parse on this host, we get this error
LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
lr.setThrown(e);
lr.setParameters(new Object[]{address});
LOGGER.log(lr);
}
}
// allow the administrator to manually specify the host name as a fallback. HUDSON-5373
cachedHostName = channel.call(new GetFallbackName());
hostNameCached = true;
return cachedHostName;
}
/**
* Starts executing a fly-weight task.
*/
/*package*/ final void startFlyWeightTask(WorkUnit p) {
OneOffExecutor e = new OneOffExecutor(this);
e.start(p);
oneOffExecutors.add(e);
}
/*package*/ final void remove(OneOffExecutor e) {
oneOffExecutors.remove(e);
}
private static class ListPossibleNames extends MasterToSlaveCallable<List<String>,IOException> {
/**
* In the normal case we would use {@link Computer} as the logger's name, however to
* do that we would have to send the {@link Computer} class over to the remote classloader
* and then it would need to be loaded, which pulls in {@link Jenkins} and loads that
* and then that fails to load as you are not supposed to do that. Another option
* would be to export the logger over remoting, with increased complexity as a result.
* Instead we just use a loger based on this class name and prevent any references to
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<String>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName());
Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
InetAddress ia = e.nextElement();
if(ia.isLoopbackAddress()) {
LOGGER.log(Level.FINE, "{0} is a loopback address", ia);
continue;
}
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia);
continue;
}
LOGGER.log(Level.FINE, "{0} is a viable candidate", ia);
names.add(ia.getHostAddress());
}
}
return names;
}
private static final long serialVersionUID = 1L;
}
private static class GetFallbackName extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
return System.getProperty("host.name");
}
private static final long serialVersionUID = 1L;
}
public static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "Computer.threadPoolForRemoting"))));
//
//
// UI
//
//
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds());
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", getBuilds().failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName() + suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp);
}
@RequirePOST
public HttpResponse doToggleOffline(@QueryParameter String offlineMessage) throws IOException, ServletException {
if(!temporarilyOffline) {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(!temporarilyOffline,
new OfflineCause.UserCause(User.current(), offlineMessage));
} else {
checkPermission(CONNECT);
setTemporarilyOffline(!temporarilyOffline,null);
}
return HttpResponses.redirectToDot();
}
@RequirePOST
public HttpResponse doChangeOfflineCause(@QueryParameter String offlineMessage) throws IOException, ServletException {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(true,
new OfflineCause.UserCause(User.current(), offlineMessage));
return HttpResponses.redirectToDot();
}
public Api getApi() {
return new Api(this);
}
/**
* Dumps the contents of the export table.
*/
public void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
// this is a debug probe and may expose sensitive information
checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("text/plain");
PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req));
VirtualChannel vc = getChannel();
if (vc instanceof Channel) {
w.println("Master to slave");
((Channel)vc).dumpExportTable(w);
w.flush(); // flush here once so that even if the dump from the slave fails, the client gets some useful info
w.println("\n\n\nSlave to master");
w.print(vc.call(new DumpExportTableTask()));
} else {
w.println(Messages.Computer_BadChannel());
}
w.close();
}
private static final class DumpExportTableTask extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Channel.current().dumpExportTable(pw);
pw.close();
return sw.toString();
}
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_script.jelly");
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_scriptText.jelly");
}
protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
/**
* Accepts the update to the node configuration.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(CONFIGURE);
String name = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name"));
Jenkins.checkGoodName(name);
Node node = getNode();
if (node == null) {
throw new ServletException("No such node " + nodeName);
}
Node result = node.reconfigure(req, req.getSubmittedForm());
replaceBy(result);
// take the user back to the slave top page.
rsp.sendRedirect2("../" + result.getNodeName() + '/');
}
/**
* Accepts <tt>config.xml</tt> submission, as well as serve it.
*/
@WebMethod(name = "config.xml")
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
if (req.getMethod().equals("GET")) {
// read
checkPermission(EXTENDED_READ);
rsp.setContentType("application/xml");
Node node = getNode();
if (node == null) {
throw HttpResponses.notFound();
}
Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream());
return;
}
if (req.getMethod().equals("POST")) {
// submission
updateByXml(req.getInputStream());
return;
}
// huh?
rsp.sendError(SC_BAD_REQUEST);
}
/**
* Replaces the current {@link Node} by another one.
*/
private void replaceBy(final Node newNode) throws ServletException, IOException {
final Jenkins app = Jenkins.getInstance();
// use the queue lock until Nodes has a way of directly modifying a single node.
Queue.withLock(new NotReallyRoleSensitiveCallable<Void, IOException>() {
public Void call() throws IOException {
List<Node> nodes = new ArrayList<Node>(app.getNodes());
Node node = getNode();
int i = (node != null) ? nodes.indexOf(node) : -1;
if(i<0) {
throw new IOException("This slave appears to be removed while you were editing the configuration");
}
nodes.set(i, newNode);
app.setNodes(nodes);
return null;
}
});
}
/**
* Updates Job by its XML definition.
*
* @since 1.526
*/
public void updateByXml(final InputStream source) throws IOException, ServletException {
checkPermission(CONFIGURE);
Node result = (Node)Jenkins.XSTREAM2.fromXML(source);
replaceBy(result);
}
/**
* Really deletes the slave.
*/
@RequirePOST
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
Node node = getNode();
if (node != null) {
Jenkins.getInstance().removeNode(node);
} else {
AbstractCIBase app = Jenkins.getInstance();
app.removeComputer(this);
}
return new HttpRedirect("..");
}
/**
* Blocks until the node becomes online/offline.
*/
@CLIMethod(name="wait-node-online")
public void waitUntilOnline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOnline())
statusChangeLock.wait(1000);
}
}
@CLIMethod(name="wait-node-offline")
public void waitUntilOffline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOffline())
statusChangeLock.wait(1000);
}
}
/**
* Handles incremental log.
*/
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req, rsp);
}
/**
* Gets the current {@link Computer} that the build is running.
* This method only works when called during a build, such as by
* {@link hudson.tasks.Publisher}, {@link hudson.tasks.BuildWrapper}, etc.
* @return the {@link Computer} associated with {@link Executor#currentExecutor}, or (consistently as of 1.591) null if not on an executor thread
*/
public static @Nullable Computer currentComputer() {
Executor e = Executor.currentExecutor();
return e != null ? e.getOwner() : null;
}
/**
* Returns {@code true} if the computer is accepting tasks. Needed to allow slaves programmatic suspension of task
* scheduling that does not overlap with being offline.
*
* @return {@code true} if the computer is accepting tasks
* @see hudson.slaves.RetentionStrategy#isAcceptingTasks(Computer)
* @see hudson.model.Node#isAcceptingTasks()
*/
@OverrideMustInvoke(When.ANYTIME)
public boolean isAcceptingTasks() {
final Node node = getNode();
return getRetentionStrategy().isAcceptingTasks(this) && (node == null || node.isAcceptingTasks());
}
/**
* Used for CLI binding.
*/
@CLIResolver
public static Computer resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Slave name, or empty string for master") String name) throws CmdLineException {
Jenkins h = Jenkins.getInstance();
Computer item = h.getComputer(name);
if (item==null) {
List<String> names = new ArrayList<String>();
for (Computer c : h.getComputers())
if (c.getName().length()>0)
names.add(c.getName());
throw new CmdLineException(null,Messages.Computer_NoSuchSlaveExists(name,EditDistance.findNearest(name,names)));
}
return item;
}
/**
* Relocate log files in the old location to the new location.
*
* Files were used to be $JENKINS_ROOT/slave-NAME.log (and .1, .2, ...)
* but now they are at $JENKINS_ROOT/logs/slaves/NAME/slave.log (and .1, .2, ...)
*
* @see #getLogFile()
*/
@Initializer
public static void relocateOldLogs() {
relocateOldLogs(Jenkins.getInstance().getRootDir());
}
/*package*/ static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessful=f.renameTo(newLocation);
if (relocationSuccessful) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
/**
* A value class to provide a consistent snapshot view of the state of an executor to avoid race conditions
* during rendering of the executors list.
*
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public static class DisplayExecutor implements ModelObject {
@Nonnull
private final String displayName;
@Nonnull
private final String url;
@Nonnull
private final Executor executor;
public DisplayExecutor(@Nonnull String displayName, @Nonnull String url, @Nonnull Executor executor) {
this.displayName = displayName;
this.url = url;
this.executor = executor;
}
@Override
@Nonnull
public String getDisplayName() {
return displayName;
}
@Nonnull
public String getUrl() {
return url;
}
@Nonnull
public Executor getExecutor() {
return executor;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DisplayExecutor that = (DisplayExecutor) o;
if (!executor.equals(that.executor)) {
return false;
}
return true;
}
@Extension(ordinal = Double.MAX_VALUE)
@Restricted(DoNotUse.class)
public static class InternalComputerListener extends ComputerListener {
@Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
c.cachedEnvironment = null;
}
}
@Override
public int hashCode() {
return executor.hashCode();
}
}
/**
* Used to trace requests to terminate a computer.
*
* @since 1.607
*/
public static class TerminationRequest extends RuntimeException {
private final long when;
public TerminationRequest(String message) {
super(message);
this.when = System.currentTimeMillis();
}
/**
* Returns the when the termination request was created.
*
* @return the difference, measured in milliseconds, between
* the time of the termination request and midnight, January 1, 1970 UTC.
*/
public long getWhen() {
return when;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title());
public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._Computer_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.COMPUTER);
/**
* @since 1.532
*/
public static final Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._Computer_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.COMPUTER});
public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._Computer_DeletePermission_Description(), Permission.DELETE, PermissionScope.COMPUTER);
public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._Computer_CreatePermission_Description(), Permission.CREATE, PermissionScope.COMPUTER);
public static final Permission DISCONNECT = new Permission(PERMISSIONS,"Disconnect", Messages._Computer_DisconnectPermission_Description(), Jenkins.ADMINISTER, PermissionScope.COMPUTER);
public static final Permission CONNECT = new Permission(PERMISSIONS,"Connect", Messages._Computer_ConnectPermission_Description(), DISCONNECT, PermissionScope.COMPUTER);
public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._Computer_BuildPermission_Description(), Permission.WRITE, PermissionScope.COMPUTER);
private static final Logger LOGGER = Logger.getLogger(Computer.class.getName());
}
| add GuardedBy("hudson.model.Queue.lock") to setNumExecutors
| core/src/main/java/hudson/model/Computer.java | add GuardedBy("hudson.model.Queue.lock") to setNumExecutors | <ide><path>ore/src/main/java/hudson/model/Computer.java
<ide> *
<ide> * @param number of executors
<ide> */
<add> @GuardedBy("hudson.model.Queue.lock")
<ide> private void setNumExecutors(int n) {
<ide> this.numExecutors = n;
<ide> final int diff = executors.size()-n; |
|
JavaScript | mit | bbc656208ca1f007268b2786ae766822ad8f5e22 | 0 | Crimx/crx-saladict,Crimx/crx-saladict | /**
* Wraps chrome extension apis
*/
export const storage = {
sync: {
get: storageGet('sync'),
set: storageSet('sync')
},
local: {
get: storageGet('local'),
set: storageSet('local')
},
listen: storageListen,
addListener: storageListen,
on: storageListen
}
/**
* Wraps in-app runtime.sendMessage and tabs.sendMessage
* Does not warp cross extension messaging!
*/
export const message = {
send: messageSend,
fire: messageSend,
emit: messageSend,
listen: messageListen,
addListener: messageListen,
on: messageListen
}
export default {
storage,
message
}
function storageGet (storageArea) {
/**
* @param {string|array|Object|null} [keys] keys to get values
* @param {function} [cb] callback with storage items or on failure
* @returns {Promise|undefined} returns a promise with the result if callback is missed
* @see https://developer.chrome.com/extensions/storage#type-StorageArea
*/
return function get (keys, cb) {
if (typeof keys === 'function') {
cb = keys
return chrome.storage[storageArea].get(cb)
} else if (typeof cb === 'function') {
return chrome.storage[storageArea].get(keys, cb)
} else {
return new Promise((resolve, reject) => {
chrome.storage[storageArea].get(keys, data => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message)
} else if (!data || Object.keys(data).length < 1) {
reject({})
} else {
resolve(data)
}
})
})
}
}
}
function storageSet (storageArea) {
/**
* @param {object} items items to set
* @param {function} [cb] Callback on success, or on failure
* @returns {Promise|undefined} returns a promise if callback is missed
* @see https://developer.chrome.com/extensions/storage#type-StorageArea
*/
return function set (items, cb) {
if (typeof cb === 'function') {
return chrome.storage[storageArea].set(items, cb)
} else {
return new Promise((resolve, reject) => {
chrome.storage[storageArea].set(items, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message)
} else {
resolve()
}
})
})
}
}
}
/**
* Listens to a specific key or uses the generic addListener
* @param {string|number} [key] key to listen to
* @param {function} cb callback function
* @see https://developer.chrome.com/extensions/storage#event-onChanged
*/
function storageListen (key, cb) {
if (typeof key === 'function') {
cb = key
chrome.storage.onChanged.addListener(cb)
} else if (typeof cb === 'function') {
chrome.storage.onChanged.addListener((changes, areaName) => {
if (changes[key]) {
cb(changes, areaName)
}
})
}
}
/**
* @param {number|string} [tabId] send to a specific tab
* @param {object} message should be a JSON-ifiable object
* @param {function} [cb] response callback
* @returns {Promise|undefined} returns a promise with the response if callback is missed
* @see https://developer.chrome.com/extensions/runtime#method-sendMessage
* @see https://developer.chrome.com/extensions/tabs#method-sendMessage
*/
function messageSend (tabId, message, cb) {
if (tabId === Object(tabId)) {
cb = message
message = tabId
if (typeof cb === 'function') {
return chrome.runtime.sendMessage(message, cb)
} else {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, response => {
resolve(response)
})
})
}
}
if (typeof cb === 'function') {
return chrome.tabs.sendMessage(tabId, message, cb)
} else {
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(tabId, message, response => {
resolve(response)
})
})
}
}
/**
* Listens to a specific message or uses the generic onMessage.addListener
* @param {string|number} [msg] message to listen to
* @param {function} cb callback function
* @see https://developer.chrome.com/extensions/runtime#event-onMessage
*/
function messageListen (msg, cb) {
if (typeof msg === 'function') {
cb = msg
chrome.runtime.onMessage.addListener(cb)
} else if (typeof cb === 'function') {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message && message.msg === msg) {
return cb(message, sender, sendResponse)
}
})
}
}
| src/helpers/chrome-api.js | /**
* Wraps chrome extension apis
*/
export const storage = {
sync: {
get: storageGet('sync'),
set: storageSet('sync')
},
local: {
get: storageGet('local'),
set: storageSet('local')
},
listen: storageListen,
addListener: storageListen,
on: storageListen
}
/**
* Wraps in-app runtime.sendMessage and tabs.sendMessage
* Does not warp cross extension messaging!
*/
export const message = {
send: messageSend,
fire: messageSend,
emit: messageSend,
listen: messageListen,
addListener: messageListen,
on: messageListen
}
export default {
storage,
message
}
function storageGet (storageArea) {
/**
* @param {string|array|Object|null} [keys] keys to get values
* @param {function} [cb] callback with storage items or on failure
* @returns {Promise|undefined} returns a promise with the result if callback is missed
* @see https://developer.chrome.com/extensions/storage#type-StorageArea
*/
return function get (keys, cb) {
if (typeof cb === 'function') {
return chrome.storage[storageArea].get(keys, cb)
} else {
return new Promise((resolve, reject) => {
chrome.storage[storageArea].get(keys, data => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message)
} else if (!data || Object.keys(data).length < 1) {
reject({})
} else {
resolve(data)
}
})
})
}
}
}
function storageSet (storageArea) {
/**
* @param {object} items items to set
* @param {function} [cb] Callback on success, or on failure
* @returns {Promise|undefined} returns a promise if callback is missed
* @see https://developer.chrome.com/extensions/storage#type-StorageArea
*/
return function set (items, cb) {
if (typeof cb === 'function') {
return chrome.storage[storageArea].set(items, cb)
} else {
return new Promise((resolve, reject) => {
chrome.storage[storageArea].set(items, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message)
} else {
resolve()
}
})
})
}
}
}
/**
* Listens to a specific key or uses the generic addListener
* @param {string|number} [key] key to listen to
* @param {function} cb callback function
* @see https://developer.chrome.com/extensions/storage#event-onChanged
*/
function storageListen (key, cb) {
if (typeof key === 'function') {
cb = key
chrome.storage.onChanged.addListener(cb)
} else if (typeof cb === 'function') {
chrome.storage.onChanged.addListener((changes, areaName) => {
if (changes[key]) {
cb(changes, areaName)
}
})
}
}
/**
* @param {number|string} [tabId] send to a specific tab
* @param {object} message should be a JSON-ifiable object
* @param {function} [cb] response callback
* @returns {Promise|undefined} returns a promise with the response if callback is missed
* @see https://developer.chrome.com/extensions/runtime#method-sendMessage
* @see https://developer.chrome.com/extensions/tabs#method-sendMessage
*/
function messageSend (tabId, message, cb) {
if (tabId === Object(tabId)) {
cb = message
message = tabId
if (typeof cb === 'function') {
return chrome.runtime.sendMessage(message, cb)
} else {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, response => {
resolve(response)
})
})
}
}
if (typeof cb === 'function') {
return chrome.tabs.sendMessage(tabId, message, cb)
} else {
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(tabId, message, response => {
resolve(response)
})
})
}
}
/**
* Listens to a specific message or uses the generic onMessage.addListener
* @param {string|number} [msg] message to listen to
* @param {function} cb callback function
* @see https://developer.chrome.com/extensions/runtime#event-onMessage
*/
function messageListen (msg, cb) {
if (typeof msg === 'function') {
cb = msg
chrome.runtime.onMessage.addListener(cb)
} else if (typeof cb === 'function') {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message && message.msg === msg) {
return cb(message, sender, sendResponse)
}
})
}
}
| Fixed keys is optional
| src/helpers/chrome-api.js | Fixed keys is optional | <ide><path>rc/helpers/chrome-api.js
<ide> * @see https://developer.chrome.com/extensions/storage#type-StorageArea
<ide> */
<ide> return function get (keys, cb) {
<del> if (typeof cb === 'function') {
<add> if (typeof keys === 'function') {
<add> cb = keys
<add> return chrome.storage[storageArea].get(cb)
<add> } else if (typeof cb === 'function') {
<ide> return chrome.storage[storageArea].get(keys, cb)
<ide> } else {
<ide> return new Promise((resolve, reject) => { |
|
Java | apache-2.0 | 25c64e86ea19d2f1821271430bdc5cb292ff9811 | 0 | RuthRainbow/anemone | package group7.anemone.Genetics;
import group7.anemone.Agent;
import group7.anemone.MNetwork.MFactory;
import group7.anemone.MNetwork.MNeuronParams;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
public class God implements Serializable{
private static final long serialVersionUID = 619717007643693268L;
/** Start of possible graphical vars **/
// Mutation chances:
public double structuralMutationChance = 0.9f;
public double addConnectionChance = 0.8f;
public double addNodeChance = 0.8f;
public double weightMutationChance = 0.8f;
// (chance of decrease is 1 - the chance of increase)
public double weightIncreaseChance = 0.5f;
//TODO add to interface :)
public double parameterMutationChance = 0.8f;
public double parameterIncreaseChance = 0.5f;
// Crossover chances:
public double twinChance = 0.05f;
public double matchedGeneChance = 0.5f;
public double offspringProportion = 0.3f; // ALSO COMPLETELY ARBITRARY
// Parameters for use in difference calculation (can be tweaked).
public double c1 = 0.45f; //weighting of excess genes
public double c2 = 0.5f; //weighting of disjoint genes
public double c3 = 0.5f; //weighting of weight differences
// Threshold for max distance between species member and representative.
// INCREASE THIS IF YOU THINK THERE ARE TOO MANY SPECIES!
public double compatibilityThreshold = 0.8;
public double minReproduced = 5;
/** End of possible graphical vars **/
private double bestFitness;
private double worstFitness;
private double averageFitness;
//private int noImprovementCount = 0;
// ************* THIS DEPENDS ON MINIMAL NETWORK ****************
private int nextEdgeMarker;
private int nextNodeMarker;
private ArrayList<Gene> newGenes;
// The ordered list of all species, with each represented by a member from the
// previous generation.
private ArrayList<Species> species;
// The distances between all genes:
private ConcurrentHashMap<Pair<AgentFitness>, Double> distances;
public God() {
this.species = new ArrayList<Species>();
this.distances = new ConcurrentHashMap<God.Pair<AgentFitness>, Double>();
}
// This is inside it's own method to make unittesting easier.
public double getRandom() {
return Math.random();
}
// Method to breed the entire population without species.
protected HashMap<Genome, Integer> BreedPopulation(ArrayList<Agent> agents) {
newGenes = new ArrayList<Gene>();
ArrayList<AgentFitness> selectedAgents = Selection(agents);
ArrayList<Genome> children = GenerateChildren(selectedAgents);
HashMap<Genome, Integer> childrenSpecies = new HashMap<Genome, Integer>();
for (Genome child : children) {
childrenSpecies.put(child, 0);
}
return childrenSpecies;
}
public ArrayList<Genome> BreedWithSpecies(ArrayList<Agent> agents, boolean fitnessOnly) {
newGenes = new ArrayList<Gene>();
if (species.size() == 0) {
species.add(new Species(new AgentFitness(agents.get(0)),0));
nextNodeMarker = agents.get(0).getStringRep().getNodes().size();
nextEdgeMarker = agents.get(0).getStringRep().getGene().length;
}
CountDownLatch latch = new CountDownLatch(agents.size() * species.size());
// Set up threads for each distance calculation to speed this up.
for (Agent agent : agents) {
AgentFitness thisAgent = new AgentFitness(agent);
for (Species specie : species) {
AgentFitness speciesRep = specie.rep;
if (!distances.containsKey(new Pair<AgentFitness>(thisAgent, speciesRep))) {
Runnable r = new CalcDistance(thisAgent, speciesRep, latch);
Thread thread = new Thread(r);
thread.run();
} else {
latch.countDown();
}
}
}
// Wait for all threads to complete:
try {
latch.await();
} catch (InterruptedException e) {
// Continue; we'll just have to calculate the distances in sequence.
}
propagateFitnesses(agents);
shareFitnesses();
ArrayList<Genome> children = new ArrayList<Genome>();
// Breed each species
for (Species specie : species) {
ArrayList<Genome> speciesChildren =
breedSpecies(specie, agents.size(), fitnessOnly);
children.addAll(speciesChildren);
}
// Pre calculate the distances of new children so this is faster next round.
Runnable r = new CalcAllDistances(children);
Thread thread = new Thread(r);
thread.run();
return children;
}
// Copy across agent's fitness from simulation to specie members.
private void propagateFitnesses(ArrayList<Agent> agents) {
for (Agent agent : agents) {
boolean speciesFound = false;
for (Species specie : species) {
for (AgentFitness member : specie.members) {
if (member.stringRep.equals(agent.getStringRep())) {
member.fitness = agent.getFitness();
speciesFound = true;
break;
}
}
}
// This case could happen if the main species sorter thread was slower than the sim.
if (!speciesFound) {
AgentFitness thisAgent = new AgentFitness(agent);
sortIntoSpecies(thisAgent);
}
}
}
// Sort given AgentFitness into a species or create a new one.
private void sortIntoSpecies(AgentFitness thisAgent) {
Genome genome = thisAgent.stringRep;
boolean foundSpecies = false;
for (Species specie : species) {
AgentFitness rep = specie.rep;
double dist = getDistance(thisAgent, rep);
if (dist < compatibilityThreshold) {
foundSpecies = true;
specie.addMember(thisAgent);
genome.setSpecies(specie.id);
break;
}
}
if (!foundSpecies) {
int newSpeciesId = species.size();
species.add(new Species(thisAgent, newSpeciesId));
genome.setSpecies(newSpeciesId);
}
}
private ArrayList<Genome> breedSpecies(Species specie, int popSize, boolean fitnessOnly) {
ArrayList<Genome> children = new ArrayList<Genome>();
if (specie.members.size() < 2) {
for (AgentFitness agent : specie.members) {
children.add(agent.stringRep);
children.add(new Genome(
mutate(agent.stringRep).getGene(),
agent.stringRep.getNodes(),
agent.stringRep.getSpeciesId(),
agent.stringRep,
agent.stringRep));
}
return children;
}
double summedFitness = 0;
for (AgentFitness agent : specie.members) {
summedFitness += agent.fitness;
}
int numOffspring = Math.max(
(int) minReproduced, (int) Math.ceil(summedFitness * offspringProportion));
System.out.println("Generating " + numOffspring + " children for species " + specie.id + " summed fitness is " + summedFitness);
// Breed the top n! (Members is presorted :))
int i = 0;
// Make sure all species enter the while loop, by duplicating if only species member.
if (specie.members.size() == 1) {
specie.addMember(specie.members.get(i));
}
while (children.size() < specie.members.size()/2 && children.size() < numOffspring) {
AgentFitness mother = specie.members.get(i);
AgentFitness father = specie.members.get(i+1);
children.addAll(CreateOffspring(mother, father));
if (fitnessOnly) {
children.add(mother.stringRep);
children.add(mother.stringRep);
}
i += 2;
}
// If not enough children, repeat some random offspring:
i = 0;
while (children.size() < numOffspring) {
children.add(children.get(i % children.size()));
i += 1;
}
return children;
}
// Share fitnesses over species by updating AgentFitness objects (see NEAT paper)
protected void shareFitnesses() {
// For every species...
for (Species specie : species) {
// For every member of this species...
for (AgentFitness agent : specie.members) {
double fitnessTotal = 0;
// average fitness over all other members of this species...
for (AgentFitness member : specie.members) {
fitnessTotal += member.fitness;
}
// Check for 0 to avoid NaNs
agent.fitness = fitnessTotal == 0 ? 0 : (agent.fitness / Math.abs(fitnessTotal));
}
}
}
protected int sharingFunction(double distance) {
if (distance > compatibilityThreshold) {
return 0; // Seems pointless. Why not only compare with dudes from the same species,
// if all others will be made 0?!
} else {
return 1;
}
}
// Return computability distance between two networks (see NEAT speciation).
// Only calculate if not previously stored.
protected double getDistance(AgentFitness thisAgent, AgentFitness speciesRep) {
if (distances.contains(thisAgent)) {
return distances.get(thisAgent);
} else {
return calcDistance(thisAgent, speciesRep);
}
}
// Compute distance between thisAgent and speciesRep (see NEAT specification).
protected double calcDistance(AgentFitness thisAgent, AgentFitness speciesRep) {
Pair<AgentFitness> agentPair = new Pair<AgentFitness>(thisAgent, speciesRep);
Genome a = thisAgent.stringRep;
Genome b = speciesRep.stringRep;
int numExcess = Math.abs(a.getLength() - b.getLength());
int numDisjoint = 0;
double weightDiff = 0.0;
int minLength = Math.min(a.getLength(), b.getLength());
int maxLength = Math.max(a.getLength(), b.getLength());
for (int i = 0; i < minLength; i++) {
if (a.getXthHistoricalMarker(i) != b.getXthHistoricalMarker(i)) {
numDisjoint++;
} else {
weightDiff += Math.abs(a.getXthWeight(i) - b.getXthWeight(i));
}
}
double averageLength = (maxLength + minLength) / 2;
if (averageLength == 0) averageLength = 1; // Avoid divide by zero.
double distance = (c1*numExcess)/averageLength + (c2*numDisjoint)/averageLength + (c3*weightDiff);
// Save this distance so we don't need to recalculate:
distances.put(agentPair, distance);
return distance;
}
protected ArrayList<AgentFitness> Selection(ArrayList<Agent> agents) {
ArrayList<AgentFitness> selectedAgents = new ArrayList<AgentFitness>();
//double last_best = bestFitness;
double last_average = averageFitness;
averageFitness = 0;
for (Agent agent : agents) {
double fitness = agent.getFitness();
averageFitness += fitness;
// This number is completely arbitrary, depends on fitness function
if (fitness * getRandom() > last_average) {
selectedAgents.add(new AgentFitness(agent));
}
if (agent.getFitness() > bestFitness) {
bestFitness = agent.getFitness();
} else if (agent.getFitness() < worstFitness) {
worstFitness = agent.getFitness();
}
}
averageFitness = averageFitness / agents.size();
// Keep track of the number of generations without improvement.
/*if (last_best >= bestFitness) {
noImprovementCount++;
} else {
noImprovementCount--;
}*/
return selectedAgents;
}
protected ArrayList<Genome> GenerateChildren(
ArrayList<AgentFitness> selectedAgents) {
// Crossover - should select partner randomly (unless we are having genders).
ArrayList<Genome> children = new ArrayList<Genome>();
while (selectedAgents.size() > 1) {
AgentFitness mother = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(mother);
AgentFitness father = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(father);
/*
// If mother and father are the same, just mutate.
if (mother.getStringRep().equals(father.getStringRep())) {
children.add(mutate(mother.getStringRep()));
} else {*/
children.add(crossover(father, mother));
//}
}
ArrayList<Genome> mutatedChildren = new ArrayList<Genome>();
// Put every child through mutation process
for (Genome child : children) {
mutatedChildren.add(mutate(child));
}
return mutatedChildren;
}
protected ArrayList<Genome> createOffspring(Agent mother, Agent father) {
AgentFitness motherFitness = new AgentFitness(mother);
AgentFitness fatherFitness = new AgentFitness(father);
ArrayList<Genome> children = CreateOffspring(motherFitness, fatherFitness);
return children;
}
// Method to create offspring from 2 given parents.
protected ArrayList<Genome> CreateOffspring(
AgentFitness mother, AgentFitness father) {
newGenes = new ArrayList<Gene>();
ArrayList<Genome> children = new ArrayList<Genome>();
children.add(crossover(mother, father));
if (getRandom() < twinChance) {
children.add(crossover(mother, father));
}
for (int i = 0; i < children.size(); i++) {
children.set(i, mutate(children.get(i)));
}
return children;
}
protected Genome crossover(AgentFitness mother, AgentFitness father) {
// If an agent has no edges, it is definitely not dominant.
if (mother.stringRep.getGene().length > 0 && mother.fitness > father.fitness) {
return crossover(mother.stringRep, father.stringRep);
} else {
return crossover(father.stringRep, mother.stringRep);
}
}
// Method for crossover - return crossover method you want.
// The mother should always be the parent with the highest fitness.
// TODO may be a problem if they have equal fitness that one is always dominant
private Genome crossover(Genome dominant, Genome recessive) {
List<Gene> child = new ArrayList<Gene>();
// "Match" genes...
Map<Gene, Gene> matches = new HashMap<Gene, Gene>();
int marker = 0;
for (int i = 0; i < dominant.getLength(); i++) {
for (int j = marker; j < recessive.getLength(); j++) {
if (dominant.getXthHistoricalMarker(i) == recessive.getXthHistoricalMarker(j) ) {
marker = j + 1;
matches.put(dominant.getXthGene(i), recessive.getXthGene(j));
}
}
}
// Generate the child
for (int i = 0; i < dominant.getLength(); i++) {
Gene gene = dominant.getXthGene(i);
if (matches.containsKey(gene)) {
// Randomly select matched gene from either parent
if (getRandom() < matchedGeneChance) {
child.add(gene);
} else {
child.add(matches.get(gene));
}
} else { //Else it didn't match, take it from the dominant
child.add(gene);
}
}
Gene[] childGene = new Gene[child.size()];
for (int i = 0; i < child.size(); i++) {
childGene[i] = child.get(i);
}
Set<NeatNode> nodeSet = new HashSet<NeatNode>(dominant.getNodes());
nodeSet.addAll(recessive.getNodes());
return new Genome(childGene, new ArrayList<NeatNode>(nodeSet), -1, dominant, recessive);
}
// Possibly mutate a child structurally or by changing edge weights.
private Genome mutate(Genome child) {
child = structuralMutation(child);
parameterMutation(child);
return weightMutation(child);
}
// Mutate the parameters of a gene.
private void parameterMutation(Genome child) {
if (getRandom() < parameterMutationChance) {
NeatNode toMutate = child.getNodes().get(
(int) Math.floor(getRandom()*child.getNodes().size()));
MNeuronParams params = toMutate.getParams();
if (getRandom() < parameterIncreaseChance) {
mutateParam(params, getRandom());
} else {
mutateParam(params, -1 * getRandom());
}
}
}
// Method to mutate one of a b c or d by the given amount
private void mutateParam(MNeuronParams params, double amount) {
double random = getRandom();
if (random < 0.25) params.a += 0.01;
else if (random < 0.5) params.b += 0.01;
else if (random < 0.75) params.c += 0.01;
else params.d += 0.01;
}
// Mutate a genome structurally
private Genome structuralMutation(Genome child) {
List<Gene> edgeList = new ArrayList<Gene>();
int max = 0;
for (Gene gene : child.getGene()) {
// Copy across all genes to new child
edgeList.add(gene);
max = Math.max(gene.getIn().id, max);
max = Math.max(gene.getOut().id, max);
}
List<NeatNode> nodeList = child.getNodes();
if (getRandom() < structuralMutationChance) {
// Add a new connection between any two nodes
if (getRandom() < addConnectionChance) {
addConnection(nodeList, edgeList);
}
// Add a new node in the middle of an old connection/edge.
if (getRandom() < addNodeChance && edgeList.size() > 0) {
max = addNodeBetweenEdges(edgeList, max, nodeList);
}
}
Gene[] mutatedGeneArray = new Gene[edgeList.size()];
for (int i = 0; i < edgeList.size(); i++) {
mutatedGeneArray[i] = edgeList.get(i);
}
return new Genome(
mutatedGeneArray,
nodeList,
child.getSpeciesId(),
child.getMother(),
child.getFather());
}
// Add a connection between two existing nodes
private void addConnection(List<NeatNode> nodeList, List<Gene> edgeList) {
// Connect two arbitrary nodes - we don't care if they are already connected.
// (Similar to growing multiple synapses).
NeatNode left = nodeList.get(
(int) Math.floor(getRandom()*nodeList.size()));
NeatNode right = nodeList.get(
(int) Math.floor(getRandom()*nodeList.size()));
Gene newGene = new Gene(
nextEdgeMarker, left, right, 30.0, 1);
// If this mutated gene has already been created this gen, don't create another
for (Gene gene : newGenes) {
if (newGene.equals(gene)) {
newGene = gene;
}
}
if (!newGenes.contains(newGene)) {
nextEdgeMarker++;
newGenes.add(newGene);
edgeList.add(newGene);
}
}
// Add a node between two pre-existing edges
private int addNodeBetweenEdges(List<Gene> edgeList, int max, List<NeatNode> nodeList) {
// Choose a gene to split: (ASSUMED IT DOESN'T MATTER IF ALREADY AN EDGE BETWEEN)
Gene toMutate = edgeList.get(
(int) Math.floor(getRandom() * edgeList.size()));
edgeList.remove(toMutate);
// Make a new intermediate node TODO can do this more randomly than default params.
// Increment max to keep track of max node id.
max += 1;
NeatNode newNode = new NeatNode(nextNodeMarker, MFactory.createRSNeuronParams());
nodeList.add(newNode);
nextNodeMarker++;
Gene newLeftGene = new Gene(nextEdgeMarker, toMutate.getIn(), newNode, 30.0, 1);
nextEdgeMarker++;
edgeList.add(newLeftGene);
// Weight should be the same as the current Gene between this two nodes:
Gene newRightGene = new Gene(
nextEdgeMarker, newNode, toMutate.getOut(), toMutate.getWeight(), 1);
nextEdgeMarker++;
edgeList.add(newRightGene);
return max;
}
// Each weight is subject to random mutation.
private Genome weightMutation(Genome child) {
for (Gene gene : child.getGene()) {
if (getRandom() < weightMutationChance) {
if (getRandom() < weightIncreaseChance) {
gene.addWeight(getRandom());
} else {
gene.addWeight(-1 * getRandom());
}
}
}
return child;
}
// Return the string representation of a new agent.
protected Gene[] RandomlyGenerate() {
throw new NotImplementedException();
}
public class NotImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotImplementedException(){}
}
// Class to hold two objects together so we can map to a distance.
private class Pair<E> {
private E first;
private E second;
public Pair(E first, E second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Pair<?>)) {
return false;
} else {
// We need pairs to be of the same type to compare.
@SuppressWarnings("unchecked")
Pair<E> otherPair = (Pair<E>) other;
if (this.first == otherPair.first && this.second == otherPair.second ||
this.first == otherPair.second && this.second == otherPair.first) {
return true;
} else {
return false;
}
}
}
public String toString() {
return "(" + first.toString() + ", " + second.toString() + ")";
}
}
// Class used to hold an entire species.
private class Species {
private ArrayList<AgentFitness> members;
private AgentFitness rep;
private int id;
public Species(AgentFitness rep, int id) {
this.rep = rep;
members = new ArrayList<AgentFitness>();
members.add(rep);
this.id =id;
}
private void addMember(AgentFitness newMember) {
members.add(newMember);
Collections.sort(members);
}
private void clear() {
members.clear();
members.add(rep);
}
}
// This class is used so we can easily compare agents by fitness.
// Also used to be more lightweight than Agent class.
private class AgentFitness implements Comparable<AgentFitness> {
private Genome stringRep;
private double fitness;
public AgentFitness(Agent agent) {
this.stringRep = agent.getStringRep();
this.fitness = agent.getFitness();
}
public AgentFitness(Genome genome) {
this.stringRep = genome;
this.fitness = 0;
}
public int compareTo(AgentFitness other) {
if (this.fitness < other.fitness) {
return 1;
} else if (this.fitness > other.fitness) {
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Genome: " + this.stringRep + " fitness: " + this.fitness;
}
}
/* Calculate distances whilst the simulation is running. */
private class CalcAllDistances implements Runnable {
private ArrayList<Genome> agents;
public CalcAllDistances(ArrayList<Genome> allChildren) {
this.agents = allChildren;
}
public synchronized void run() {
// Clear species for a new gen
for (Species specie : species) {
specie.clear();
}
// Put each agent given for reproduction into a species.
for (Genome agent : this.agents) {
AgentFitness thisAgent = new AgentFitness(agent);
sortIntoSpecies(thisAgent);
}
}
}
private class CalcDistance implements Runnable {
private AgentFitness thisAgent;
private AgentFitness speciesRep;
private CountDownLatch latch;
public CalcDistance(AgentFitness thisAgent, AgentFitness speciesRep, CountDownLatch latch) {
this.thisAgent = thisAgent;
this.speciesRep = speciesRep;
this.latch = latch;
}
public synchronized void run() {
calcDistance(thisAgent, speciesRep);
latch.countDown();
}
}
} | src/main/java/group7/anemone/Genetics/God.java | package group7.anemone.Genetics;
import group7.anemone.Agent;
import group7.anemone.MNetwork.MFactory;
import group7.anemone.MNetwork.MNeuronParams;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
public class God implements Serializable{
private static final long serialVersionUID = 619717007643693268L;
/** Start of possible graphical vars **/
// Mutation chances:
public double structuralMutationChance = 0.9f;
public double addConnectionChance = 0.8f;
public double addNodeChance = 0.8f;
public double weightMutationChance = 0.8f;
// (chance of decrease is 1 - the chance of increase)
public double weightIncreaseChance = 0.5f;
//TODO add to interface :)
public double parameterMutationChance = 0.8f;
public double parameterIncreaseChance = 0.5f;
// Crossover chances:
public double twinChance = 0.05f;
public double matchedGeneChance = 0.5f;
public double offspringProportion = 0.3f; // ALSO COMPLETELY ARBITRARY
// Parameters for use in difference calculation (can be tweaked).
public double c1 = 0.45f; //weighting of excess genes
public double c2 = 0.5f; //weighting of disjoint genes
public double c3 = 0.5f; //weighting of weight differences
// Threshold for max distance between species member and representative.
// INCREASE THIS IF YOU THINK THERE ARE TOO MANY SPECIES!
public double compatibilityThreshold = 0.8;
public double minReproduced = 5;
/** End of possible graphical vars **/
private double bestFitness;
private double worstFitness;
private double averageFitness;
//private int noImprovementCount = 0;
// ************* THIS DEPENDS ON MINIMAL NETWORK ****************
private int nextEdgeMarker;
private int nextNodeMarker;
private ArrayList<Gene> newGenes;
// The ordered list of all species, with each represented by a member from the
// previous generation.
private ArrayList<Species> species;
// The distances between all genes:
private ConcurrentHashMap<Pair<AgentFitness>, Double> distances;
public God() {
this.species = new ArrayList<Species>();
this.distances = new ConcurrentHashMap<God.Pair<AgentFitness>, Double>();
}
// This is inside it's own method to make unittesting easier.
public double getRandom() {
return Math.random();
}
// Method to breed the entire population without species.
protected HashMap<Genome, Integer> BreedPopulation(ArrayList<Agent> agents) {
newGenes = new ArrayList<Gene>();
ArrayList<AgentFitness> selectedAgents = Selection(agents);
ArrayList<Genome> children = GenerateChildren(selectedAgents);
HashMap<Genome, Integer> childrenSpecies = new HashMap<Genome, Integer>();
for (Genome child : children) {
childrenSpecies.put(child, 0);
}
return childrenSpecies;
}
public ArrayList<Genome> BreedWithSpecies(ArrayList<Agent> agents, boolean fitnessOnly) {
newGenes = new ArrayList<Gene>();
if (species.size() == 0) {
species.add(new Species(new AgentFitness(agents.get(0)),0));
nextNodeMarker = agents.get(0).getStringRep().getNodes().size();
nextEdgeMarker = agents.get(0).getStringRep().getGene().length;
}
CountDownLatch latch = new CountDownLatch(agents.size() * species.size());
// Set up threads for each distance calculation to speed this up.
for (Agent agent : agents) {
AgentFitness thisAgent = new AgentFitness(agent);
for (Species specie : species) {
AgentFitness speciesRep = specie.rep;
if (!distances.containsKey(new Pair<AgentFitness>(thisAgent, speciesRep))) {
Runnable r = new CalcDistance(thisAgent, speciesRep, latch);
Thread thread = new Thread(r);
thread.run();
} else {
latch.countDown();
}
}
}
// Wait for all threads to complete:
try {
latch.await();
} catch (InterruptedException e) {
// Continue; we'll just have to calculate the distances in sequence.
}
PropagateFitnesses(agents);
shareFitnesses();
ArrayList<Genome> children = new ArrayList<Genome>();
// Breed each species
for (Species specie : species) {
ArrayList<Genome> speciesChildren =
breedSpecies(specie, agents.size(), fitnessOnly);
children.addAll(speciesChildren);
}
// Pre calculate the distances of new children so this is faster next round.
Runnable r = new CalcAllDistances(children);
Thread thread = new Thread(r);
thread.run();
return children;
}
// Copy across agent's fitness from simulation to specie members.
private void PropagateFitnesses(ArrayList<Agent> agents) {
for (Agent agent : agents) {
for (Species specie : species) {
for (AgentFitness member : specie.members) {
if (member.stringRep.equals(agent.getStringRep())) {
member.fitness = agent.getFitness();
break;
}
}
}
}
}
private ArrayList<Genome> breedSpecies(Species specie, int popSize, boolean fitnessOnly) {
ArrayList<Genome> children = new ArrayList<Genome>();
if (specie.members.size() < 2) {
for (AgentFitness agent : specie.members) {
children.add(agent.stringRep);
children.add(new Genome(
mutate(agent.stringRep).getGene(),
agent.stringRep.getNodes(),
agent.stringRep.getSpeciesId(),
agent.stringRep,
agent.stringRep));
}
return children;
}
double summedFitness = 0;
for (AgentFitness agent : specie.members) {
summedFitness += agent.fitness;
}
int numOffspring = Math.max(
(int) minReproduced, (int) Math.ceil(summedFitness * offspringProportion));
System.out.println("Generating " + numOffspring + " children for species " + specie.id + " summed fitness is " + summedFitness);
// Breed the top n! (Members is presorted :))
int i = 0;
// Make sure all species enter the while loop, by duplicating if only species member.
if (specie.members.size() == 1) {
specie.addMember(specie.members.get(i));
}
while (children.size() < specie.members.size()/2 && children.size() < numOffspring) {
AgentFitness mother = specie.members.get(i);
AgentFitness father = specie.members.get(i+1);
children.addAll(CreateOffspring(mother, father));
if (fitnessOnly) {
children.add(mother.stringRep);
children.add(mother.stringRep);
}
i += 2;
}
// If not enough children, repeat some random offspring:
i = 0;
while (children.size() < numOffspring) {
children.add(children.get(i % children.size()));
i += 1;
}
return children;
}
// Share fitnesses over species by updating AgentFitness objects (see NEAT paper)
protected void shareFitnesses() {
// For every species...
for (Species specie : species) {
// For every member of this species...
for (AgentFitness agent : specie.members) {
double fitnessTotal = 0;
// average fitness over all other members of this species...
for (AgentFitness member : specie.members) {
fitnessTotal += member.fitness;
}
// Check for 0 to avoid NaNs
agent.fitness = fitnessTotal == 0 ? 0 : (agent.fitness / Math.abs(fitnessTotal));
}
}
}
protected int sharingFunction(double distance) {
if (distance > compatibilityThreshold) {
return 0; // Seems pointless. Why not only compare with dudes from the same species,
// if all others will be made 0?!
} else {
return 1;
}
}
// Return computability distance between two networks (see NEAT speciation).
// Only calculate if not previously stored.
protected double getDistance(AgentFitness thisAgent, AgentFitness speciesRep) {
if (distances.contains(thisAgent)) {
return distances.get(thisAgent);
} else {
return calcDistance(thisAgent, speciesRep);
}
}
// Compute distance between thisAgent and speciesRep (see NEAT specification).
protected double calcDistance(AgentFitness thisAgent, AgentFitness speciesRep) {
Pair<AgentFitness> agentPair = new Pair<AgentFitness>(thisAgent, speciesRep);
Genome a = thisAgent.stringRep;
Genome b = speciesRep.stringRep;
int numExcess = Math.abs(a.getLength() - b.getLength());
int numDisjoint = 0;
double weightDiff = 0.0;
int minLength = Math.min(a.getLength(), b.getLength());
int maxLength = Math.max(a.getLength(), b.getLength());
for (int i = 0; i < minLength; i++) {
if (a.getXthHistoricalMarker(i) != b.getXthHistoricalMarker(i)) {
numDisjoint++;
} else {
weightDiff += Math.abs(a.getXthWeight(i) - b.getXthWeight(i));
}
}
double averageLength = (maxLength + minLength) / 2;
if (averageLength == 0) averageLength = 1; // Avoid divide by zero.
double distance = (c1*numExcess)/averageLength + (c2*numDisjoint)/averageLength + (c3*weightDiff);
// Save this distance so we don't need to recalculate:
distances.put(agentPair, distance);
return distance;
}
protected ArrayList<AgentFitness> Selection(ArrayList<Agent> agents) {
ArrayList<AgentFitness> selectedAgents = new ArrayList<AgentFitness>();
//double last_best = bestFitness;
double last_average = averageFitness;
averageFitness = 0;
for (Agent agent : agents) {
double fitness = agent.getFitness();
averageFitness += fitness;
// This number is completely arbitrary, depends on fitness function
if (fitness * getRandom() > last_average) {
selectedAgents.add(new AgentFitness(agent));
}
if (agent.getFitness() > bestFitness) {
bestFitness = agent.getFitness();
} else if (agent.getFitness() < worstFitness) {
worstFitness = agent.getFitness();
}
}
averageFitness = averageFitness / agents.size();
// Keep track of the number of generations without improvement.
/*if (last_best >= bestFitness) {
noImprovementCount++;
} else {
noImprovementCount--;
}*/
return selectedAgents;
}
protected ArrayList<Genome> GenerateChildren(
ArrayList<AgentFitness> selectedAgents) {
// Crossover - should select partner randomly (unless we are having genders).
ArrayList<Genome> children = new ArrayList<Genome>();
while (selectedAgents.size() > 1) {
AgentFitness mother = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(mother);
AgentFitness father = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(father);
/*
// If mother and father are the same, just mutate.
if (mother.getStringRep().equals(father.getStringRep())) {
children.add(mutate(mother.getStringRep()));
} else {*/
children.add(crossover(father, mother));
//}
}
ArrayList<Genome> mutatedChildren = new ArrayList<Genome>();
// Put every child through mutation process
for (Genome child : children) {
mutatedChildren.add(mutate(child));
}
return mutatedChildren;
}
protected ArrayList<Genome> createOffspring(Agent mother, Agent father) {
AgentFitness motherFitness = new AgentFitness(mother);
AgentFitness fatherFitness = new AgentFitness(father);
ArrayList<Genome> children = CreateOffspring(motherFitness, fatherFitness);
return children;
}
// Method to create offspring from 2 given parents.
protected ArrayList<Genome> CreateOffspring(
AgentFitness mother, AgentFitness father) {
newGenes = new ArrayList<Gene>();
ArrayList<Genome> children = new ArrayList<Genome>();
children.add(crossover(mother, father));
if (getRandom() < twinChance) {
children.add(crossover(mother, father));
}
for (int i = 0; i < children.size(); i++) {
children.set(i, mutate(children.get(i)));
}
return children;
}
protected Genome crossover(AgentFitness mother, AgentFitness father) {
// If an agent has no edges, it is definitely not dominant.
if (mother.stringRep.getGene().length > 0 && mother.fitness > father.fitness) {
return crossover(mother.stringRep, father.stringRep);
} else {
return crossover(father.stringRep, mother.stringRep);
}
}
// Method for crossover - return crossover method you want.
// The mother should always be the parent with the highest fitness.
// TODO may be a problem if they have equal fitness that one is always dominant
private Genome crossover(Genome dominant, Genome recessive) {
List<Gene> child = new ArrayList<Gene>();
// "Match" genes...
Map<Gene, Gene> matches = new HashMap<Gene, Gene>();
int marker = 0;
for (int i = 0; i < dominant.getLength(); i++) {
for (int j = marker; j < recessive.getLength(); j++) {
if (dominant.getXthHistoricalMarker(i) == recessive.getXthHistoricalMarker(j) ) {
marker = j + 1;
matches.put(dominant.getXthGene(i), recessive.getXthGene(j));
}
}
}
// Generate the child
for (int i = 0; i < dominant.getLength(); i++) {
Gene gene = dominant.getXthGene(i);
if (matches.containsKey(gene)) {
// Randomly select matched gene from either parent
if (getRandom() < matchedGeneChance) {
child.add(gene);
} else {
child.add(matches.get(gene));
}
} else { //Else it didn't match, take it from the dominant
child.add(gene);
}
}
Gene[] childGene = new Gene[child.size()];
for (int i = 0; i < child.size(); i++) {
childGene[i] = child.get(i);
}
Set<NeatNode> nodeSet = new HashSet<NeatNode>(dominant.getNodes());
nodeSet.addAll(recessive.getNodes());
return new Genome(childGene, new ArrayList<NeatNode>(nodeSet), -1, dominant, recessive);
}
// Possibly mutate a child structurally or by changing edge weights.
private Genome mutate(Genome child) {
child = structuralMutation(child);
parameterMutation(child);
return weightMutation(child);
}
// Mutate the parameters of a gene.
private void parameterMutation(Genome child) {
if (getRandom() < parameterMutationChance) {
NeatNode toMutate = child.getNodes().get(
(int) Math.floor(getRandom()*child.getNodes().size()));
MNeuronParams params = toMutate.getParams();
if (getRandom() < parameterIncreaseChance) {
mutateParam(params, getRandom());
} else {
mutateParam(params, -1 * getRandom());
}
}
}
// Method to mutate one of a b c or d by the given amount
private void mutateParam(MNeuronParams params, double amount) {
double random = getRandom();
if (random < 0.25) params.a += 0.01;
else if (random < 0.5) params.b += 0.01;
else if (random < 0.75) params.c += 0.01;
else params.d += 0.01;
}
// Mutate a genome structurally
private Genome structuralMutation(Genome child) {
List<Gene> edgeList = new ArrayList<Gene>();
int max = 0;
for (Gene gene : child.getGene()) {
// Copy across all genes to new child
edgeList.add(gene);
max = Math.max(gene.getIn().id, max);
max = Math.max(gene.getOut().id, max);
}
List<NeatNode> nodeList = child.getNodes();
if (getRandom() < structuralMutationChance) {
// Add a new connection between any two nodes
if (getRandom() < addConnectionChance) {
addConnection(nodeList, edgeList);
}
// Add a new node in the middle of an old connection/edge.
if (getRandom() < addNodeChance && edgeList.size() > 0) {
max = addNodeBetweenEdges(edgeList, max, nodeList);
}
}
Gene[] mutatedGeneArray = new Gene[edgeList.size()];
for (int i = 0; i < edgeList.size(); i++) {
mutatedGeneArray[i] = edgeList.get(i);
}
return new Genome(
mutatedGeneArray,
nodeList,
child.getSpeciesId(),
child.getMother(),
child.getFather());
}
// Add a connection between two existing nodes
private void addConnection(List<NeatNode> nodeList, List<Gene> edgeList) {
// Connect two arbitrary nodes - we don't care if they are already connected.
// (Similar to growing multiple synapses).
NeatNode left = nodeList.get(
(int) Math.floor(getRandom()*nodeList.size()));
NeatNode right = nodeList.get(
(int) Math.floor(getRandom()*nodeList.size()));
Gene newGene = new Gene(
nextEdgeMarker, left, right, 30.0, 1);
// If this mutated gene has already been created this gen, don't create another
for (Gene gene : newGenes) {
if (newGene.equals(gene)) {
newGene = gene;
}
}
if (!newGenes.contains(newGene)) {
nextEdgeMarker++;
newGenes.add(newGene);
edgeList.add(newGene);
}
}
// Add a node between two pre-existing edges
private int addNodeBetweenEdges(List<Gene> edgeList, int max, List<NeatNode> nodeList) {
// Choose a gene to split: (ASSUMED IT DOESN'T MATTER IF ALREADY AN EDGE BETWEEN)
Gene toMutate = edgeList.get(
(int) Math.floor(getRandom() * edgeList.size()));
edgeList.remove(toMutate);
// Make a new intermediate node TODO can do this more randomly than default params.
// Increment max to keep track of max node id.
max += 1;
NeatNode newNode = new NeatNode(nextNodeMarker, MFactory.createRSNeuronParams());
nodeList.add(newNode);
nextNodeMarker++;
Gene newLeftGene = new Gene(nextEdgeMarker, toMutate.getIn(), newNode, 30.0, 1);
nextEdgeMarker++;
edgeList.add(newLeftGene);
// Weight should be the same as the current Gene between this two nodes:
Gene newRightGene = new Gene(
nextEdgeMarker, newNode, toMutate.getOut(), toMutate.getWeight(), 1);
nextEdgeMarker++;
edgeList.add(newRightGene);
return max;
}
// Each weight is subject to random mutation.
private Genome weightMutation(Genome child) {
for (Gene gene : child.getGene()) {
if (getRandom() < weightMutationChance) {
if (getRandom() < weightIncreaseChance) {
gene.addWeight(getRandom());
} else {
gene.addWeight(-1 * getRandom());
}
}
}
return child;
}
// Return the string representation of a new agent.
protected Gene[] RandomlyGenerate() {
throw new NotImplementedException();
}
public class NotImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotImplementedException(){}
}
// Class to hold two objects together so we can map to a distance.
private class Pair<E> {
private E first;
private E second;
public Pair(E first, E second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Pair<?>)) {
return false;
} else {
// We need pairs to be of the same type to compare.
@SuppressWarnings("unchecked")
Pair<E> otherPair = (Pair<E>) other;
if (this.first == otherPair.first && this.second == otherPair.second ||
this.first == otherPair.second && this.second == otherPair.first) {
return true;
} else {
return false;
}
}
}
public String toString() {
return "(" + first.toString() + ", " + second.toString() + ")";
}
}
// Class used to hold an entire species.
private class Species {
private ArrayList<AgentFitness> members;
private AgentFitness rep;
private int id;
public Species(AgentFitness rep, int id) {
this.rep = rep;
members = new ArrayList<AgentFitness>();
members.add(rep);
this.id =id;
}
private void addMember(AgentFitness newMember) {
members.add(newMember);
Collections.sort(members);
}
private void clear() {
members.clear();
members.add(rep);
}
}
// This class is used so we can easily compare agents by fitness.
// Also used to be more lightweight than Agent class.
private class AgentFitness implements Comparable<AgentFitness> {
private Genome stringRep;
private double fitness;
public AgentFitness(Agent agent) {
this.stringRep = agent.getStringRep();
this.fitness = agent.getFitness();
}
public AgentFitness(Genome genome) {
this.stringRep = genome;
this.fitness = 0;
}
public int compareTo(AgentFitness other) {
if (this.fitness < other.fitness) {
return 1;
} else if (this.fitness > other.fitness) {
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Genome: " + this.stringRep + " fitness: " + this.fitness;
}
}
/* Calculate distances whilst the simulation is running. */
private class CalcAllDistances implements Runnable {
private ArrayList<Genome> agents;
public CalcAllDistances(ArrayList<Genome> allChildren) {
this.agents = allChildren;
}
public synchronized void run() {
// Clear species for a new gen
for (Species specie : species) {
specie.clear();
}
// Put each agent given for reproduction into a species.
for (Genome agent : this.agents) {
AgentFitness thisAgent = new AgentFitness(agent);
boolean foundSpecies = false;
for (Species specie : species) {
AgentFitness rep = specie.rep;
double dist = getDistance(thisAgent, rep);
if (dist < compatibilityThreshold) {
foundSpecies = true;
specie.addMember(thisAgent);
agent.setSpecies(specie.id);
break;
}
}
if (!foundSpecies) {
int newSpeciesId = species.size();
species.add(new Species(thisAgent, newSpeciesId));
agent.setSpecies(newSpeciesId);
}
}
}
}
private class CalcDistance implements Runnable {
private AgentFitness thisAgent;
private AgentFitness speciesRep;
private CountDownLatch latch;
public CalcDistance(AgentFitness thisAgent, AgentFitness speciesRep, CountDownLatch latch) {
this.thisAgent = thisAgent;
this.speciesRep = speciesRep;
this.latch = latch;
}
public synchronized void run() {
calcDistance(thisAgent, speciesRep);
latch.countDown();
}
}
} | if sort itno species thread too slow, still sort into species...
| src/main/java/group7/anemone/Genetics/God.java | if sort itno species thread too slow, still sort into species... | <ide><path>rc/main/java/group7/anemone/Genetics/God.java
<ide> public double c1 = 0.45f; //weighting of excess genes
<ide> public double c2 = 0.5f; //weighting of disjoint genes
<ide> public double c3 = 0.5f; //weighting of weight differences
<add>
<ide> // Threshold for max distance between species member and representative.
<ide> // INCREASE THIS IF YOU THINK THERE ARE TOO MANY SPECIES!
<ide> public double compatibilityThreshold = 0.8;
<ide> // Continue; we'll just have to calculate the distances in sequence.
<ide> }
<ide>
<del> PropagateFitnesses(agents);
<add> propagateFitnesses(agents);
<ide>
<ide> shareFitnesses();
<ide> ArrayList<Genome> children = new ArrayList<Genome>();
<ide> }
<ide>
<ide> // Copy across agent's fitness from simulation to specie members.
<del> private void PropagateFitnesses(ArrayList<Agent> agents) {
<add> private void propagateFitnesses(ArrayList<Agent> agents) {
<ide> for (Agent agent : agents) {
<add> boolean speciesFound = false;
<ide> for (Species specie : species) {
<ide> for (AgentFitness member : specie.members) {
<ide> if (member.stringRep.equals(agent.getStringRep())) {
<ide> member.fitness = agent.getFitness();
<add> speciesFound = true;
<ide> break;
<ide> }
<ide> }
<ide> }
<add> // This case could happen if the main species sorter thread was slower than the sim.
<add> if (!speciesFound) {
<add> AgentFitness thisAgent = new AgentFitness(agent);
<add> sortIntoSpecies(thisAgent);
<add> }
<add> }
<add> }
<add>
<add> // Sort given AgentFitness into a species or create a new one.
<add> private void sortIntoSpecies(AgentFitness thisAgent) {
<add> Genome genome = thisAgent.stringRep;
<add> boolean foundSpecies = false;
<add> for (Species specie : species) {
<add> AgentFitness rep = specie.rep;
<add> double dist = getDistance(thisAgent, rep);
<add>
<add> if (dist < compatibilityThreshold) {
<add> foundSpecies = true;
<add> specie.addMember(thisAgent);
<add> genome.setSpecies(specie.id);
<add> break;
<add> }
<add> }
<add> if (!foundSpecies) {
<add> int newSpeciesId = species.size();
<add> species.add(new Species(thisAgent, newSpeciesId));
<add> genome.setSpecies(newSpeciesId);
<ide> }
<ide> }
<ide>
<ide> // Put each agent given for reproduction into a species.
<ide> for (Genome agent : this.agents) {
<ide> AgentFitness thisAgent = new AgentFitness(agent);
<del> boolean foundSpecies = false;
<del>
<del> for (Species specie : species) {
<del> AgentFitness rep = specie.rep;
<del> double dist = getDistance(thisAgent, rep);
<del>
<del> if (dist < compatibilityThreshold) {
<del> foundSpecies = true;
<del> specie.addMember(thisAgent);
<del> agent.setSpecies(specie.id);
<del> break;
<del> }
<del> }
<del> if (!foundSpecies) {
<del> int newSpeciesId = species.size();
<del> species.add(new Species(thisAgent, newSpeciesId));
<del> agent.setSpecies(newSpeciesId);
<del> }
<add> sortIntoSpecies(thisAgent);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | b46a77447b5ecb304bb049e7c3052cdf721dff6d | 0 | btkelly/gandalf,btkelly/gandalf | /**
* Copyright 2016 Bryan Kelly
*
* 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.github.btkelly.gandalf.holders;
import android.content.Context;
import android.support.annotation.StringRes;
import io.github.btkelly.gandalf.R;
/**
* Holds strings that will be displayed in the AlertDialog built by BootstrapDialogUtil
*/
public class DialogStringsHolder {
private Context context;
private String updateAvailableTitle;
private String updateRequiredTitle;
private String alertTitle;
private String downloadUpdateButton;
private String skipUpdateButton;
private String closeAppButton;
private String okButton;
public DialogStringsHolder(Context context) {
this.context = context;
}
public String getUpdateAvailableTitle() {
if (updateAvailableTitle == null) {
setUpdateAvailableTitle(R.string.update_available_title);
}
return updateAvailableTitle;
}
public String getUpdateRequiredTitle() {
if (updateRequiredTitle == null) {
setUpdateRequiredTitle(R.string.update_required_title);
}
return updateRequiredTitle;
}
public String getAlertTitle() {
if (alertTitle == null) {
setUpdateAvailableTitle(R.string.alert_title);
}
return alertTitle;
}
public String getDownloadUpdateButtonText() {
if (downloadUpdateButton == null) {
setDownloadUpdateButtonText(R.string.download_update_button);
}
return downloadUpdateButton;
}
public String getSkipUpdateButtonText() {
if (skipUpdateButton == null) {
setSkipUpdateButtonText(R.string.skip_update_button);
}
return skipUpdateButton;
}
public String getCloseAppButtonText() {
if (closeAppButton == null) {
setCloseAppButtonText(R.string.close_app_button);
}
return closeAppButton;
}
public String getOkButtonText() {
if (okButton == null) {
setOkButtonText(R.string.ok_button);
}
return okButton;
}
public void setUpdateAvailableTitle(@StringRes int updateAvailableTitle) {
this.updateAvailableTitle = context.getResources().getString(updateAvailableTitle);
}
public void setUpdateAvailableTitle(String updateAvailableTitle) {
this.updateAvailableTitle = updateAvailableTitle;
}
public void setUpdateRequiredTitle(@StringRes int updateRequiredTitle) {
this.updateRequiredTitle = context.getResources().getString(updateRequiredTitle);
}
public void setUpdateRequiredTitle(String updateRequiredTitle) {
this.updateRequiredTitle = updateRequiredTitle;
}
public void setDownloadUpdateButtonText(@StringRes int downloadUpdateButton) {
this.downloadUpdateButton = context.getResources().getString(downloadUpdateButton);
}
public void setDownloadUpdateButtonText(String downloadUpdateButton) {
this.downloadUpdateButton = downloadUpdateButton;
}
public void setSkipUpdateButtonText(@StringRes int skipUpdateButton) {
this.skipUpdateButton = context.getResources().getString(skipUpdateButton);
}
public void setSkipUpdateButtonText(String skipUpdateButton) {
this.skipUpdateButton = skipUpdateButton;
}
public void setCloseAppButtonText(@StringRes int closeAppButton) {
this.closeAppButton = context.getResources().getString(closeAppButton);
}
public void setCloseAppButtonText(String closeAppButton) {
this.closeAppButton = closeAppButton;
}
public void setAlertTitle(@StringRes int alertTitle) {
this.alertTitle = context.getResources().getString(alertTitle);
}
public void setAlertTitle(String alertTitle) {
this.alertTitle = alertTitle;
}
public void setOkButtonText(@StringRes int okButton) {
this.okButton = context.getResources().getString(okButton);
}
public void setOkButtonText(String okButton) {
this.okButton = okButton;
}
}
| gandalf/src/main/java/io/github/btkelly/gandalf/holders/DialogStringsHolder.java | /**
* Copyright 2016 Bryan Kelly
*
* 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.github.btkelly.gandalf.holders;
import android.content.Context;
import android.support.annotation.StringRes;
import io.github.btkelly.gandalf.R;
/**
* Holds strings that will be displayed in the AlertDialog built by BootstrapDialogUtil
*/
public class DialogStringsHolder {
private Context context;
private String updateAvailableTitle;
private String updateRequiredTitle;
private String alertTitle;
private String downloadUpdateButton;
private String skipUpdateButton;
private String closeAppButton;
private String okButton;
public DialogStringsHolder(Context context) {
this.context = context;
setUpdateAvailableTitle(R.string.update_available_title);
setUpdateRequiredTitle(R.string.update_required_title);
setDownloadUpdateButtonText(R.string.download_update_button);
setSkipUpdateButtonText(R.string.skip_update_button);
setCloseAppButtonText(R.string.close_app_button);
setAlertTitle(R.string.alert_title);
setOkButtonText(R.string.ok_button);
}
public String getUpdateAvailableTitle() {
if (updateAvailableTitle == null) {
setUpdateAvailableTitle(R.string.update_available_title);
}
return updateAvailableTitle;
}
public String getUpdateRequiredTitle() {
if (updateRequiredTitle == null) {
setUpdateRequiredTitle(R.string.update_required_title);
}
return updateRequiredTitle;
}
public String getAlertTitle() {
if (alertTitle == null) {
setUpdateAvailableTitle(R.string.alert_title);
}
return alertTitle;
}
public String getDownloadUpdateButtonText() {
if (downloadUpdateButton == null) {
setDownloadUpdateButtonText(R.string.download_update_button);
}
return downloadUpdateButton;
}
public String getSkipUpdateButtonText() {
if (skipUpdateButton == null) {
setSkipUpdateButtonText(R.string.skip_update_button);
}
return skipUpdateButton;
}
public String getCloseAppButtonText() {
if (closeAppButton == null) {
setCloseAppButtonText(R.string.close_app_button);
}
return closeAppButton;
}
public String getOkButtonText() {
if (okButton == null) {
setOkButtonText(R.string.ok_button);
}
return okButton;
}
public void setUpdateAvailableTitle(@StringRes int updateAvailableTitle) {
this.updateAvailableTitle = context.getResources().getString(updateAvailableTitle);
}
public void setUpdateAvailableTitle(String updateAvailableTitle) {
this.updateAvailableTitle = updateAvailableTitle;
}
public void setUpdateRequiredTitle(@StringRes int updateRequiredTitle) {
this.updateRequiredTitle = context.getResources().getString(updateRequiredTitle);
}
public void setUpdateRequiredTitle(String updateRequiredTitle) {
this.updateRequiredTitle = updateRequiredTitle;
}
public void setDownloadUpdateButtonText(@StringRes int downloadUpdateButton) {
this.downloadUpdateButton = context.getResources().getString(downloadUpdateButton);
}
public void setDownloadUpdateButtonText(String downloadUpdateButton) {
this.downloadUpdateButton = downloadUpdateButton;
}
public void setSkipUpdateButtonText(@StringRes int skipUpdateButton) {
this.skipUpdateButton = context.getResources().getString(skipUpdateButton);
}
public void setSkipUpdateButtonText(String skipUpdateButton) {
this.skipUpdateButton = skipUpdateButton;
}
public void setCloseAppButtonText(@StringRes int closeAppButton) {
this.closeAppButton = context.getResources().getString(closeAppButton);
}
public void setCloseAppButtonText(String closeAppButton) {
this.closeAppButton = closeAppButton;
}
public void setAlertTitle(@StringRes int alertTitle) {
this.alertTitle = context.getResources().getString(alertTitle);
}
public void setAlertTitle(String alertTitle) {
this.alertTitle = alertTitle;
}
public void setOkButtonText(@StringRes int okButton) {
this.okButton = context.getResources().getString(okButton);
}
public void setOkButtonText(String okButton) {
this.okButton = okButton;
}
}
| Remove useless calls to setters in DialogStringsHolder's constructor
| gandalf/src/main/java/io/github/btkelly/gandalf/holders/DialogStringsHolder.java | Remove useless calls to setters in DialogStringsHolder's constructor | <ide><path>andalf/src/main/java/io/github/btkelly/gandalf/holders/DialogStringsHolder.java
<ide>
<ide> public DialogStringsHolder(Context context) {
<ide> this.context = context;
<del> setUpdateAvailableTitle(R.string.update_available_title);
<del> setUpdateRequiredTitle(R.string.update_required_title);
<del> setDownloadUpdateButtonText(R.string.download_update_button);
<del> setSkipUpdateButtonText(R.string.skip_update_button);
<del> setCloseAppButtonText(R.string.close_app_button);
<del> setAlertTitle(R.string.alert_title);
<del> setOkButtonText(R.string.ok_button);
<ide> }
<ide>
<ide> public String getUpdateAvailableTitle() { |
|
Java | bsd-3-clause | e703e7f2641bad2ff4abc21837d5ca885df43122 | 0 | Axway/VersionOne.Integration.Jenkins,versionone/VersionOne.Integration.Jenkins,versionone/VersionOne.Integration.Jenkins,Axway/VersionOne.Integration.Jenkins,Axway/VersionOne.Integration.Jenkins | package com.versionone.hudson;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.tasks.Publisher;
import hudson.tasks.Shell;
import hudson.util.DescribableList;
import org.apache.commons.io.FileUtils;
import org.jvnet.hudson.test.HudsonTestCase;
/*
public class AppTest extends HudsonTestCase {
/* //TODO review and fix it
public void test1() throws Exception {
FreeStyleProject project = createFreeStyleProject();
DescribableList<Publisher, Descriptor<Publisher>> publishers = project.getPublishersList();
VersionOneNotifier versionOneNotifier = new VersionOneNotifier();
versionOneNotifier.getDescriptor().setData("http://fake_domen/VersionOne/", "admin", "admin", "[A-Z]{1,2}-[0-9]+", "Number");
publishers.add(versionOneNotifier);
FreeStyleBuild build = project.scheduleBuild2(0).get();
System.out.println(build.getDisplayName() + " completed");
String s = FileUtils.readFileToString(build.getLogFile());
assertTrue(s.contains("VersionOne:"));
}
*/
/*
public void test2() throws IOException, SAXException {
final HtmlPage page = new WebClient().goTo("configure");
assertElementPresentByName(page, "com-versionone-hudson-VersionOneNotifier");
}
*/
/**
* Verifies that the specified page contains an element with the specified ID.
*
* @param page the page to check
* @param name the expected Name of an element in the page
*/
/*
public static void assertElementPresentByName(final HtmlPage page, final String name) {
try {
page.getElementsByName(name);
} catch (final ElementNotFoundException e) {
throw new AssertionError("The page does not contain an element with name '" + name + "'.");
}
}
}
*/ | src/test/java/com/versionone/hudson/AppTest.java | package com.versionone.hudson;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.tasks.Publisher;
import hudson.tasks.Shell;
import hudson.util.DescribableList;
import org.apache.commons.io.FileUtils;
import org.jvnet.hudson.test.HudsonTestCase;
public class AppTest extends HudsonTestCase {
/* //TODO review and fix it
public void test1() throws Exception {
FreeStyleProject project = createFreeStyleProject();
DescribableList<Publisher, Descriptor<Publisher>> publishers = project.getPublishersList();
VersionOneNotifier versionOneNotifier = new VersionOneNotifier();
versionOneNotifier.getDescriptor().setData("http://fake_domen/VersionOne/", "admin", "admin", "[A-Z]{1,2}-[0-9]+", "Number");
publishers.add(versionOneNotifier);
FreeStyleBuild build = project.scheduleBuild2(0).get();
System.out.println(build.getDisplayName() + " completed");
String s = FileUtils.readFileToString(build.getLogFile());
assertTrue(s.contains("VersionOne:"));
}
*/
/*
public void test2() throws IOException, SAXException {
final HtmlPage page = new WebClient().goTo("configure");
assertElementPresentByName(page, "com-versionone-hudson-VersionOneNotifier");
}
*/
/**
* Verifies that the specified page contains an element with the specified ID.
*
* @param page the page to check
* @param name the expected Name of an element in the page
*/
public static void assertElementPresentByName(final HtmlPage page, final String name) {
try {
page.getElementsByName(name);
} catch (final ElementNotFoundException e) {
throw new AssertionError("The page does not contain an element with name '" + name + "'.");
}
}
} | commented test
git-svn-id: 88f7df0341149fb5a53df8bd0fa6fd6589aa8338@42310 542498e7-56f8-f544-a0f2-a85913ac812a
| src/test/java/com/versionone/hudson/AppTest.java | commented test | <ide><path>rc/test/java/com/versionone/hudson/AppTest.java
<ide> import hudson.util.DescribableList;
<ide> import org.apache.commons.io.FileUtils;
<ide> import org.jvnet.hudson.test.HudsonTestCase;
<del>
<add>/*
<ide> public class AppTest extends HudsonTestCase {
<ide>
<ide> /* //TODO review and fix it
<ide> * @param page the page to check
<ide> * @param name the expected Name of an element in the page
<ide> */
<add>/*
<ide> public static void assertElementPresentByName(final HtmlPage page, final String name) {
<ide> try {
<ide> page.getElementsByName(name);
<ide> }
<ide> }
<ide> }
<add>*/ |
|
Java | apache-2.0 | 1daf8102cdceb1d97f16db7d328c2702a385ed7c | 0 | gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom | package stroom.event.logging.impl;
import stroom.activity.api.CurrentActivity;
import stroom.event.logging.api.ObjectInfoProvider;
import stroom.event.logging.api.ObjectType;
import stroom.event.logging.api.StroomEventLoggingService;
import stroom.security.api.SecurityContext;
import stroom.security.mock.MockSecurityContext;
import stroom.util.logging.LogUtil;
import stroom.util.shared.BuildInfo;
import stroom.util.shared.HasName;
import event.logging.AuthenticateEventAction;
import event.logging.BaseObject;
import event.logging.Data;
import event.logging.OtherObject;
import event.logging.Outcome;
import event.logging.Resource;
import event.logging.User;
import event.logging.ViewEventAction;
import event.logging.impl.LogReceiver;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class TestStroomEventLoggingServiceImpl {
private static final String TYPE_ID = "typeId";
private static final String DESCRIPTION = "I did something";
private SecurityContext securityContext = new MockSecurityContext();
@Mock
private HttpServletRequest httpServletRequest;
@Mock
private CurrentActivity currentActivity;
@Mock
private BuildInfo buildInfo;
private StroomEventLoggingService stroomEventLoggingService;
private BaseObject testObj = OtherObject.builder().withDescription("Test").build();
@BeforeEach
void setup() {
final Map<ObjectType, Provider<ObjectInfoProvider>> objectInfoProviderMap =
new HashMap<>();
objectInfoProviderMap.put(new ObjectType(TestObj.class), () -> new TestObjInfoProvider());
stroomEventLoggingService = new StroomEventLoggingServiceImpl(
new LoggingConfig(),
securityContext,
() -> httpServletRequest,
objectInfoProviderMap,
currentActivity,
() -> buildInfo);
LocalLogReceiver.getEvents()
.clear();
// Make the event logger use our log receiver so we can get the events
System.setProperty("event.logging.logreceiver", LocalLogReceiver.class.getName());
}
@Test
void testLoggedAction_failure() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedAction(
TYPE_ID,
DESCRIPTION,
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedAction_failure_overwriteOutcome() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedAction(
TYPE_ID,
DESCRIPTION,
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.withOutcome(Outcome.builder()
.withSuccess(true) // will be overwritten
.withDescription("It worked") // will be overwritten
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedAction_success() {
AtomicBoolean wasWorkDone = new AtomicBoolean(false);
stroomEventLoggingService.loggedAction(
"typeId",
"desc",
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.build(),
() -> {
// Do some work
wasWorkDone.set(true);
});
assertThat(wasWorkDone)
.isTrue();
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertThat(xml)
.doesNotContainPattern("<Success>.*</Success>");
}
@Test
void testLoggedResult_failure() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedResult(
"typeId",
"desc",
AuthenticateEventAction.builder()
.withUser(User.builder()
.withName("jbloggs")
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedResult_success() {
final Boolean result = stroomEventLoggingService.loggedResult(
"typeId",
"desc",
AuthenticateEventAction.builder()
.withUser(User.builder()
.withName("jbloggs")
.build())
.build(),
() -> {
// Do some work
return true;
});
assertThat(result)
.isTrue();
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertThat(xml)
.doesNotContainPattern("<Success>.*</Success>");
}
@Test
void testDataItemCreationAndRedaction () throws Exception {
List<Data> allData = stroomEventLoggingService.getDataItems
(new TestSecretObj("test", "xyzzy", "open-sesame"));
assertThat(allData.size()).isEqualTo(4);
assertThat(allData).anyMatch(data -> data.getName().equals("name"));
assertThat(allData).anyMatch(data -> data.getName().equals("password"));
assertThat(allData).anyMatch(data -> data.getName().equals("myNewSecret"));
assertThat(allData).anyMatch(data -> data.getName().equals("secret"));
assertThat(allData).noneMatch(data -> data.getValue().equals("xyzzy"));
assertThat(allData).noneMatch(data -> data.getValue().equals("open-sesame"));
assertThat(allData.stream().filter(data -> data.getValue().equals("test"))
.collect(Collectors.toList()).size()).isEqualTo(1);
assertThat(allData.stream().filter(data -> data.getValue().equals("false"))
.collect(Collectors.toList()).size()).isEqualTo(1);
}
@Test
void testConvertPojoWithInfoPrvider () throws Exception {
BaseObject baseObject = stroomEventLoggingService.convert(new TestObj());
assertThat(baseObject).isSameAs(testObj);
}
@Test
void testConvertPojoWithoutInfoPrvider () throws Exception {
String name = "TestSecretObject1";
String typeName = TestSecretObj.class.getSimpleName();
BaseObject baseObject = stroomEventLoggingService.convert(new TestSecretObj(name, "b", "x"));
assertThat(baseObject.getType()).isEqualTo(typeName);
String description = baseObject.getDescription();
assertThat(baseObject.getName()).isEqualTo(name);
assertThat(description).contains(name);
assertThat(description).contains(typeName);
}
private void assertTagValue(final String xml, final String tag, final String value) {
assertThat(xml)
.contains(LogUtil.message("<{}>{}</{}>", tag, value, tag));
}
public static class LocalLogReceiver implements LogReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(LocalLogReceiver.class);
private static final List<String> EVENTS = new ArrayList<>();
@Override
public void log(final String data) {
LOGGER.info("Received event\n{}", data);
EVENTS.add(data);
}
public LocalLogReceiver() {
}
public static List<String> getEvents() {
return EVENTS;
}
}
public static class TestObj {
}
public class TestObjInfoProvider implements ObjectInfoProvider {
@Override
public BaseObject createBaseObject(final Object object) {
return testObj;
}
@Override
public String getObjectType(final Object object) {
return "Test Object";
}
}
public static class TestSecretObj implements HasName {
private String name;
private String password;
private String myNewSecret;
private boolean secret;
public TestSecretObj (String name, String password, String myNewSecret){
this.name = name;
this.password = password;
this.myNewSecret = myNewSecret;
}
public String getMyNewSecret() {
return myNewSecret;
}
public void setMyNewSecret(final String myNewSecret) {
this.myNewSecret = myNewSecret;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public Boolean isSecret() {
return secret;
}
@Override
public void setName(final String name) {
}
}
} | stroom-event-logging/stroom-event-logging-impl/src/test/java/stroom/event/logging/impl/TestStroomEventLoggingServiceImpl.java | package stroom.event.logging.impl;
import stroom.activity.api.CurrentActivity;
import stroom.event.logging.api.ObjectInfoProvider;
import stroom.event.logging.api.ObjectType;
import stroom.event.logging.api.StroomEventLoggingService;
import stroom.security.api.SecurityContext;
import stroom.security.mock.MockSecurityContext;
import stroom.util.logging.LogUtil;
import stroom.util.shared.BuildInfo;
import stroom.util.shared.HasName;
import event.logging.AuthenticateEventAction;
import event.logging.BaseObject;
import event.logging.Data;
import event.logging.OtherObject;
import event.logging.Outcome;
import event.logging.Resource;
import event.logging.User;
import event.logging.ViewEventAction;
import event.logging.impl.LogReceiver;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class TestStroomEventLoggingServiceImpl {
private static final String TYPE_ID = "typeId";
private static final String DESCRIPTION = "I did something";
private SecurityContext securityContext = new MockSecurityContext();
@Mock
private HttpServletRequest httpServletRequest;
@Mock
private CurrentActivity currentActivity;
@Mock
private BuildInfo buildInfo;
private StroomEventLoggingService stroomEventLoggingService;
private BaseObject testObj = OtherObject.builder().withDescription("Test").build();
@BeforeEach
void setup() {
final Map<ObjectType, Provider<ObjectInfoProvider>> objectInfoProviderMap =
new HashMap<>();
objectInfoProviderMap.put(new ObjectType(TestObj.class), () -> new TestObjInfoProvider());
stroomEventLoggingService = new StroomEventLoggingServiceImpl(
securityContext,
() -> httpServletRequest,
objectInfoProviderMap,
currentActivity,
() -> buildInfo);
LocalLogReceiver.getEvents()
.clear();
// Make the event logger use our log receiver so we can get the events
System.setProperty("event.logging.logreceiver", LocalLogReceiver.class.getName());
}
@Test
void testLoggedAction_failure() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedAction(
TYPE_ID,
DESCRIPTION,
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedAction_failure_overwriteOutcome() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedAction(
TYPE_ID,
DESCRIPTION,
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.withOutcome(Outcome.builder()
.withSuccess(true) // will be overwritten
.withDescription("It worked") // will be overwritten
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedAction_success() {
AtomicBoolean wasWorkDone = new AtomicBoolean(false);
stroomEventLoggingService.loggedAction(
"typeId",
"desc",
ViewEventAction.builder()
.addResource(Resource.builder()
.withURL("localhost")
.build())
.build(),
() -> {
// Do some work
wasWorkDone.set(true);
});
assertThat(wasWorkDone)
.isTrue();
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertThat(xml)
.doesNotContainPattern("<Success>.*</Success>");
}
@Test
void testLoggedResult_failure() {
final String exceptionMsg = "Bad stuff happened";
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
stroomEventLoggingService.loggedResult(
"typeId",
"desc",
AuthenticateEventAction.builder()
.withUser(User.builder()
.withName("jbloggs")
.build())
.build(),
() -> {
// Do some work
throw new RuntimeException(exceptionMsg);
});
})
.withMessage(exceptionMsg);
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertTagValue(xml, "Description", exceptionMsg);
assertTagValue(xml, "Success", "false");
}
@Test
void testLoggedResult_success() {
final Boolean result = stroomEventLoggingService.loggedResult(
"typeId",
"desc",
AuthenticateEventAction.builder()
.withUser(User.builder()
.withName("jbloggs")
.build())
.build(),
() -> {
// Do some work
return true;
});
assertThat(result)
.isTrue();
assertThat(LocalLogReceiver.getEvents())
.hasSize(1);
final String xml = LocalLogReceiver.getEvents().get(0);
assertThat(xml)
.doesNotContainPattern("<Success>.*</Success>");
}
@Test
void testDataItemCreationAndRedaction () throws Exception {
List<Data> allData = stroomEventLoggingService.getDataItems
(new TestSecretObj("test", "xyzzy", "open-sesame"));
assertThat(allData.size()).isEqualTo(4);
assertThat(allData).anyMatch(data -> data.getName().equals("name"));
assertThat(allData).anyMatch(data -> data.getName().equals("password"));
assertThat(allData).anyMatch(data -> data.getName().equals("myNewSecret"));
assertThat(allData).anyMatch(data -> data.getName().equals("secret"));
assertThat(allData).noneMatch(data -> data.getValue().equals("xyzzy"));
assertThat(allData).noneMatch(data -> data.getValue().equals("open-sesame"));
assertThat(allData.stream().filter(data -> data.getValue().equals("test"))
.collect(Collectors.toList()).size()).isEqualTo(1);
assertThat(allData.stream().filter(data -> data.getValue().equals("false"))
.collect(Collectors.toList()).size()).isEqualTo(1);
}
@Test
void testConvertPojoWithInfoPrvider () throws Exception {
BaseObject baseObject = stroomEventLoggingService.convert(new TestObj());
assertThat(baseObject).isSameAs(testObj);
}
@Test
void testConvertPojoWithoutInfoPrvider () throws Exception {
String name = "TestSecretObject1";
String typeName = TestSecretObj.class.getSimpleName();
BaseObject baseObject = stroomEventLoggingService.convert(new TestSecretObj(name, "b", "x"));
assertThat(baseObject.getType()).isEqualTo(typeName);
String description = baseObject.getDescription();
assertThat(baseObject.getName()).isEqualTo(name);
assertThat(description).contains(name);
assertThat(description).contains(typeName);
}
private void assertTagValue(final String xml, final String tag, final String value) {
assertThat(xml)
.contains(LogUtil.message("<{}>{}</{}>", tag, value, tag));
}
public static class LocalLogReceiver implements LogReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(LocalLogReceiver.class);
private static final List<String> EVENTS = new ArrayList<>();
@Override
public void log(final String data) {
LOGGER.info("Received event\n{}", data);
EVENTS.add(data);
}
public LocalLogReceiver() {
}
public static List<String> getEvents() {
return EVENTS;
}
}
public static class TestObj {
}
public class TestObjInfoProvider implements ObjectInfoProvider {
@Override
public BaseObject createBaseObject(final Object object) {
return testObj;
}
@Override
public String getObjectType(final Object object) {
return "Test Object";
}
}
public static class TestSecretObj implements HasName {
private String name;
private String password;
private String myNewSecret;
private boolean secret;
public TestSecretObj (String name, String password, String myNewSecret){
this.name = name;
this.password = password;
this.myNewSecret = myNewSecret;
}
public String getMyNewSecret() {
return myNewSecret;
}
public void setMyNewSecret(final String myNewSecret) {
this.myNewSecret = myNewSecret;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public Boolean isSecret() {
return secret;
}
@Override
public void setName(final String name) {
}
}
} | Fix compilation error
| stroom-event-logging/stroom-event-logging-impl/src/test/java/stroom/event/logging/impl/TestStroomEventLoggingServiceImpl.java | Fix compilation error | <ide><path>troom-event-logging/stroom-event-logging-impl/src/test/java/stroom/event/logging/impl/TestStroomEventLoggingServiceImpl.java
<ide> objectInfoProviderMap.put(new ObjectType(TestObj.class), () -> new TestObjInfoProvider());
<ide>
<ide> stroomEventLoggingService = new StroomEventLoggingServiceImpl(
<add> new LoggingConfig(),
<ide> securityContext,
<ide> () -> httpServletRequest,
<ide> objectInfoProviderMap, |
|
Java | apache-2.0 | dca1ed05bfccce69814fdb59b095d734d1c82de0 | 0 | kongweihan/helix,dasahcc/helix,dasahcc/helix,apache/helix,kongweihan/helix,apache/helix,dasahcc/helix,apache/helix,apache/helix,dasahcc/helix,lei-xia/helix,apache/helix,apache/helix,lei-xia/helix,lei-xia/helix,lei-xia/helix,dasahcc/helix,kongweihan/helix,lei-xia/helix,lei-xia/helix,dasahcc/helix | package org.apache.helix.monitoring.mbeans;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.helix.controller.stages.BestPossibleStateOutput;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.Partition;
import org.apache.helix.model.Resource;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskDriver;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.Workflow;
import org.apache.helix.task.WorkflowConfig;
import org.apache.helix.task.WorkflowContext;
import org.apache.log4j.Logger;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ClusterStatusMonitor implements ClusterStatusMonitorMBean {
private static final Logger LOG = Logger.getLogger(ClusterStatusMonitor.class);
public static final String CLUSTER_STATUS_KEY = "ClusterStatus";
static final String MESSAGE_QUEUE_STATUS_KEY = "MessageQueueStatus";
static final String RESOURCE_STATUS_KEY = "ResourceStatus";
public static final String PARTICIPANT_STATUS_KEY = "ParticipantStatus";
static final String CLUSTER_DN_KEY = "cluster";
static final String RESOURCE_DN_KEY = "resourceName";
static final String INSTANCE_DN_KEY = "instanceName";
static final String MESSAGE_QUEUE_DN_KEY = "messageQueue";
static final String WORKFLOW_TYPE_DN_KEY = "workflowType";
static final String JOB_TYPE_DN_KEY = "jobType";
static final String DEFAULT_WORKFLOW_JOB_TYPE = "DEFAULT";
public static final String DEFAULT_TAG = "DEFAULT";
private final String _clusterName;
private final MBeanServer _beanServer;
private Set<String> _liveInstances = Collections.emptySet();
private Set<String> _instances = Collections.emptySet();
private Set<String> _disabledInstances = Collections.emptySet();
private Map<String, Set<String>> _disabledPartitions = Collections.emptyMap();
private Map<String, Long> _instanceMsgQueueSizes = Maps.newConcurrentMap();
private final ConcurrentHashMap<String, ResourceMonitor> _resourceMbeanMap =
new ConcurrentHashMap<String, ResourceMonitor>();
private final ConcurrentHashMap<String, InstanceMonitor> _instanceMbeanMap =
new ConcurrentHashMap<String, InstanceMonitor>();
/**
* PerInstanceResource bean map: beanName->bean
*/
private final Map<PerInstanceResourceMonitor.BeanName, PerInstanceResourceMonitor> _perInstanceResourceMap =
new ConcurrentHashMap<PerInstanceResourceMonitor.BeanName, PerInstanceResourceMonitor>();
private final Map<String, WorkflowMonitor> _perTypeWorkflowMonitorMap =
new ConcurrentHashMap<String, WorkflowMonitor>();
private final Map<String, JobMonitor> _perTypeJobMonitorMap =
new ConcurrentHashMap<String, JobMonitor>();
public ClusterStatusMonitor(String clusterName) {
_clusterName = clusterName;
_beanServer = ManagementFactory.getPlatformMBeanServer();
try {
register(this, getObjectName(clusterBeanName()));
} catch (Exception e) {
LOG.error("Fail to regiter ClusterStatusMonitor", e);
}
}
public ObjectName getObjectName(String name) throws MalformedObjectNameException {
return new ObjectName(String.format("%s: %s", CLUSTER_STATUS_KEY, name));
}
// TODO remove getBeanName()?
// Used by other external JMX consumers like ingraph
public String getBeanName() {
return CLUSTER_STATUS_KEY + " " + _clusterName;
}
@Override
public long getDownInstanceGauge() {
return _instances.size() - _liveInstances.size();
}
@Override
public long getInstancesGauge() {
return _instances.size();
}
@Override
public long getDisabledInstancesGauge() {
return _disabledInstances.size();
}
@Override
public long getDisabledPartitionsGauge() {
int numDisabled = 0;
for (String instance : _disabledPartitions.keySet()) {
numDisabled += _disabledPartitions.get(instance).size();
}
return numDisabled;
}
@Override
public long getMaxMessageQueueSizeGauge() {
long maxQueueSize = 0;
for (Long queueSize : _instanceMsgQueueSizes.values()) {
if (queueSize > maxQueueSize) {
maxQueueSize = queueSize;
}
}
return maxQueueSize;
}
@Override
public long getInstanceMessageQueueBacklog() {
long sum = 0;
for (Long queueSize : _instanceMsgQueueSizes.values()) {
sum += queueSize;
}
return sum;
}
private void register(Object bean, ObjectName name) {
try {
if (_beanServer.isRegistered(name)) {
_beanServer.unregisterMBean(name);
}
} catch (Exception e) {
// OK
}
try {
LOG.info("Register MBean: " + name);
_beanServer.registerMBean(bean, name);
} catch (Exception e) {
LOG.warn("Could not register MBean: " + name, e);
}
}
private void unregister(ObjectName name) {
try {
if (_beanServer.isRegistered(name)) {
LOG.info("Unregistering " + name.toString());
_beanServer.unregisterMBean(name);
}
} catch (Exception e) {
LOG.warn("Could not unregister MBean: " + name, e);
}
}
/**
* Update the gauges for all instances in the cluster
* @param liveInstanceSet the current set of live instances
* @param instanceSet the current set of configured instances (live or other
* @param disabledInstanceSet the current set of configured instances that are disabled
* @param disabledPartitions a map of instance name to the set of partitions disabled on it
* @param tags a map of instance name to the set of tags on it
*/
public void setClusterInstanceStatus(Set<String> liveInstanceSet, Set<String> instanceSet,
Set<String> disabledInstanceSet, Map<String, Set<String>> disabledPartitions,
Map<String, Set<String>> tags) {
// Unregister beans for instances that are no longer configured
Set<String> toUnregister = Sets.newHashSet(_instanceMbeanMap.keySet());
toUnregister.removeAll(instanceSet);
try {
unregisterInstances(toUnregister);
} catch (MalformedObjectNameException e) {
LOG.error("Could not unregister instances from MBean server: " + toUnregister, e);
}
// Register beans for instances that are newly configured
Set<String> toRegister = Sets.newHashSet(instanceSet);
toRegister.removeAll(_instanceMbeanMap.keySet());
Set<InstanceMonitor> monitorsToRegister = Sets.newHashSet();
for (String instanceName : toRegister) {
InstanceMonitor bean = new InstanceMonitor(_clusterName, instanceName);
bean.updateInstance(tags.get(instanceName), disabledPartitions.get(instanceName),
liveInstanceSet.contains(instanceName), !disabledInstanceSet.contains(instanceName));
monitorsToRegister.add(bean);
}
try {
registerInstances(monitorsToRegister);
} catch (MalformedObjectNameException e) {
LOG.error("Could not register instances with MBean server: " + toRegister, e);
}
// Update all the sets
_instances = instanceSet;
_liveInstances = liveInstanceSet;
_disabledInstances = disabledInstanceSet;
_disabledPartitions = disabledPartitions;
// Update the instance MBeans
for (String instanceName : instanceSet) {
if (_instanceMbeanMap.containsKey(instanceName)) {
// Update the bean
InstanceMonitor bean = _instanceMbeanMap.get(instanceName);
String oldSensorName = bean.getSensorName();
bean.updateInstance(tags.get(instanceName), disabledPartitions.get(instanceName),
liveInstanceSet.contains(instanceName), !disabledInstanceSet.contains(instanceName));
// If the sensor name changed, re-register the bean so that listeners won't miss it
String newSensorName = bean.getSensorName();
if (!oldSensorName.equals(newSensorName)) {
try {
unregisterInstances(Arrays.asList(instanceName));
registerInstances(Arrays.asList(bean));
} catch (MalformedObjectNameException e) {
LOG.error("Could not refresh registration with MBean server: " + instanceName, e);
}
}
}
}
}
/**
* Update gauges for resource at instance level
* @param bestPossibleStates
* @param resourceMap
* @param stateModelDefMap
*/
public void setPerInstanceResourceStatus(BestPossibleStateOutput bestPossibleStates,
Map<String, InstanceConfig> instanceConfigMap, Map<String, Resource> resourceMap,
Map<String, StateModelDefinition> stateModelDefMap) {
// Convert to perInstanceResource beanName->partition->state
Map<PerInstanceResourceMonitor.BeanName, Map<Partition, String>> beanMap =
new HashMap<PerInstanceResourceMonitor.BeanName, Map<Partition, String>>();
for (String resource : bestPossibleStates.resourceSet()) {
Map<Partition, Map<String, String>> partitionStateMap =
bestPossibleStates.getResourceMap(resource);
for (Partition partition : partitionStateMap.keySet()) {
Map<String, String> instanceStateMap = partitionStateMap.get(partition);
for (String instance : instanceStateMap.keySet()) {
String state = instanceStateMap.get(instance);
PerInstanceResourceMonitor.BeanName beanName =
new PerInstanceResourceMonitor.BeanName(instance, resource);
if (!beanMap.containsKey(beanName)) {
beanMap.put(beanName, new HashMap<Partition, String>());
}
beanMap.get(beanName).put(partition, state);
}
}
}
// Unregister beans for per-instance resources that no longer exist
Set<PerInstanceResourceMonitor.BeanName> toUnregister =
Sets.newHashSet(_perInstanceResourceMap.keySet());
toUnregister.removeAll(beanMap.keySet());
try {
unregisterPerInstanceResources(toUnregister);
} catch (MalformedObjectNameException e) {
LOG.error("Fail to unregister per-instance resource from MBean server: " + toUnregister, e);
}
// Register beans for per-instance resources that are newly configured
Set<PerInstanceResourceMonitor.BeanName> toRegister = Sets.newHashSet(beanMap.keySet());
toRegister.removeAll(_perInstanceResourceMap.keySet());
Set<PerInstanceResourceMonitor> monitorsToRegister = Sets.newHashSet();
for (PerInstanceResourceMonitor.BeanName beanName : toRegister) {
PerInstanceResourceMonitor bean =
new PerInstanceResourceMonitor(_clusterName, beanName.instanceName(),
beanName.resourceName());
String stateModelDefName = resourceMap.get(beanName.resourceName()).getStateModelDefRef();
InstanceConfig config = instanceConfigMap.get(beanName.instanceName());
bean.update(beanMap.get(beanName), Sets.newHashSet(config.getTags()),
stateModelDefMap.get(stateModelDefName));
monitorsToRegister.add(bean);
}
try {
registerPerInstanceResources(monitorsToRegister);
} catch (MalformedObjectNameException e) {
LOG.error("Fail to register per-instance resource with MBean server: " + toRegister, e);
}
// Update existing beans
for (PerInstanceResourceMonitor.BeanName beanName : _perInstanceResourceMap.keySet()) {
PerInstanceResourceMonitor bean = _perInstanceResourceMap.get(beanName);
String stateModelDefName = resourceMap.get(beanName.resourceName()).getStateModelDefRef();
InstanceConfig config = instanceConfigMap.get(beanName.instanceName());
bean.update(beanMap.get(beanName), Sets.newHashSet(config.getTags()),
stateModelDefMap.get(stateModelDefName));
}
}
/**
* Indicate that a resource has been dropped, thus making it OK to drop its metrics
* @param resourceName the resource that has been dropped
*/
public void unregisterResource(String resourceName) {
if (_resourceMbeanMap.containsKey(resourceName)) {
synchronized (this) {
if (_resourceMbeanMap.containsKey(resourceName)) {
try {
unregisterResources(Arrays.asList(resourceName));
} catch (MalformedObjectNameException e) {
LOG.error("Could not unregister beans for " + resourceName, e);
}
}
}
}
}
public void setResourceStatus(ExternalView externalView, IdealState idealState,
StateModelDefinition stateModelDef) {
String topState = null;
if (stateModelDef != null) {
List<String> priorityList = stateModelDef.getStatesPriorityList();
if (!priorityList.isEmpty()) {
topState = priorityList.get(0);
}
}
try {
String resourceName = externalView.getId();
if (!_resourceMbeanMap.containsKey(resourceName)) {
synchronized (this) {
if (!_resourceMbeanMap.containsKey(resourceName)) {
ResourceMonitor bean = new ResourceMonitor(_clusterName, resourceName);
bean.updateResource(externalView, idealState, topState);
registerResources(Arrays.asList(bean));
}
}
}
ResourceMonitor bean = _resourceMbeanMap.get(resourceName);
String oldSensorName = bean.getSensorName();
bean.updateResource(externalView, idealState, topState);
String newSensorName = bean.getSensorName();
if (!oldSensorName.equals(newSensorName)) {
unregisterResources(Arrays.asList(resourceName));
registerResources(Arrays.asList(bean));
}
} catch (Exception e) {
LOG.error("Fail to set resource status, resource: " + idealState.getResourceName(), e);
}
}
public void addMessageQueueSize(String instanceName, long msgQueueSize) {
_instanceMsgQueueSizes.put(instanceName, msgQueueSize);
}
public void reset() {
LOG.info("Reset ClusterStatusMonitor");
try {
unregisterResources(_resourceMbeanMap.keySet());
_resourceMbeanMap.clear();
_instanceMsgQueueSizes.clear();
unregisterInstances(_instanceMbeanMap.keySet());
_instanceMbeanMap.clear();
unregisterPerInstanceResources(_perInstanceResourceMap.keySet());
unregister(getObjectName(clusterBeanName()));
unregisterWorkflows(_perTypeWorkflowMonitorMap.keySet());
unregisterJobs(_perTypeJobMonitorMap.keySet());
} catch (Exception e) {
LOG.error("Fail to reset ClusterStatusMonitor, cluster: " + _clusterName, e);
}
}
public void refreshWorkflowsStatus(TaskDriver driver) {
for (WorkflowMonitor workflowMonitor : _perTypeWorkflowMonitorMap.values()) {
workflowMonitor.resetGauges();
}
Map<String, WorkflowConfig> workflowConfigMap = driver.getWorkflows();
for (String workflow : workflowConfigMap.keySet()) {
if (workflowConfigMap.get(workflow).isRecurring()) {
continue;
}
WorkflowContext workflowContext = driver.getWorkflowContext(workflow);
TaskState currentState =
workflowContext == null ? TaskState.NOT_STARTED : workflowContext.getWorkflowState();
updateWorkflowGauges(workflowConfigMap.get(workflow), currentState);
}
}
public void updateWorkflowCounters(WorkflowConfig workflowConfig, TaskState to) {
String workflowType = workflowConfig.getWorkflowType();
workflowType = preProcessWorkflow(workflowType);
_perTypeWorkflowMonitorMap.get(workflowType).updateWorkflowCounters(to);
}
private void updateWorkflowGauges(WorkflowConfig workflowConfig, TaskState current) {
String workflowType = workflowConfig.getWorkflowType();
workflowType = preProcessWorkflow(workflowType);
_perTypeWorkflowMonitorMap.get(workflowType).updateWorkflowGauges(current);
}
private String preProcessWorkflow(String workflowType) {
if (workflowType == null || workflowType.length() == 0) {
workflowType = DEFAULT_WORKFLOW_JOB_TYPE;
}
if (!_perTypeWorkflowMonitorMap.containsKey(workflowType)) {
WorkflowMonitor monitor = new WorkflowMonitor(_clusterName, workflowType);
try {
registerWorkflow(monitor);
} catch (MalformedObjectNameException e) {
LOG.error("Failed to register object for workflow type : " + workflowType, e);
}
_perTypeWorkflowMonitorMap.put(workflowType, monitor);
}
return workflowType;
}
public void refreshJobsStatus(TaskDriver driver) {
for (JobMonitor jobMonitor : _perTypeJobMonitorMap.values()) {
jobMonitor.resetJobGauge();
}
for (String workflow : driver.getWorkflows().keySet()) {
Set<String> allJobs = driver.getWorkflowConfig(workflow).getJobDag().getAllNodes();
WorkflowContext workflowContext = driver.getWorkflowContext(workflow);
for (String job : allJobs) {
TaskState currentState =
workflowContext == null ? TaskState.NOT_STARTED : workflowContext.getJobState(job);
updateJobGauges(driver.getJobConfig(job), currentState);
}
}
}
public void updateJobCounters(JobConfig jobConfig, TaskState to) {
String jobType = jobConfig.getJobType();
jobType = preProcessJobMonitor(jobType);
_perTypeJobMonitorMap.get(jobType).updateJobCounters(to);
}
private void updateJobGauges(JobConfig jobConfig, TaskState current) {
// When first time for WorkflowRebalancer call, jobconfig may not ready.
// Thus only check it for gauge.
if (jobConfig == null) {
return;
}
String jobType = jobConfig.getJobType();
jobType = preProcessJobMonitor(jobType);
_perTypeJobMonitorMap.get(jobType).updateJobGauge(current);
}
private String preProcessJobMonitor(String jobType) {
if (jobType == null || jobType.length() == 0) {
jobType = DEFAULT_WORKFLOW_JOB_TYPE;
}
if (!_perTypeJobMonitorMap.containsKey(jobType)) {
JobMonitor monitor = new JobMonitor(_clusterName, jobType);
try {
registerJob(monitor);
} catch (MalformedObjectNameException e) {
LOG.error("Failed to register job type : " + jobType, e);
}
_perTypeJobMonitorMap.put(jobType, monitor);
}
return jobType;
}
private synchronized void registerInstances(Collection<InstanceMonitor> instances)
throws MalformedObjectNameException {
for (InstanceMonitor monitor : instances) {
String instanceName = monitor.getInstanceName();
String beanName = getInstanceBeanName(instanceName);
register(monitor, getObjectName(beanName));
_instanceMbeanMap.put(instanceName, monitor);
}
}
private synchronized void unregisterInstances(Collection<String> instances)
throws MalformedObjectNameException {
for (String instanceName : instances) {
String beanName = getInstanceBeanName(instanceName);
unregister(getObjectName(beanName));
}
_instanceMbeanMap.keySet().removeAll(instances);
}
private synchronized void registerResources(Collection<ResourceMonitor> resources)
throws MalformedObjectNameException {
for (ResourceMonitor monitor : resources) {
String resourceName = monitor.getResourceName();
String beanName = getResourceBeanName(resourceName);
register(monitor, getObjectName(beanName));
_resourceMbeanMap.put(resourceName, monitor);
}
}
private synchronized void unregisterResources(Collection<String> resources)
throws MalformedObjectNameException {
for (String resourceName : resources) {
String beanName = getResourceBeanName(resourceName);
unregister(getObjectName(beanName));
}
_resourceMbeanMap.keySet().removeAll(resources);
}
private synchronized void registerPerInstanceResources(
Collection<PerInstanceResourceMonitor> monitors) throws MalformedObjectNameException {
for (PerInstanceResourceMonitor monitor : monitors) {
String instanceName = monitor.getInstanceName();
String resourceName = monitor.getResourceName();
String beanName = getPerInstanceResourceBeanName(instanceName, resourceName);
register(monitor, getObjectName(beanName));
_perInstanceResourceMap.put(new PerInstanceResourceMonitor.BeanName(instanceName,
resourceName), monitor);
}
}
private synchronized void unregisterPerInstanceResources(
Collection<PerInstanceResourceMonitor.BeanName> beanNames)
throws MalformedObjectNameException {
for (PerInstanceResourceMonitor.BeanName beanName : beanNames) {
unregister(getObjectName(getPerInstanceResourceBeanName(beanName.instanceName(),
beanName.resourceName())));
}
_perInstanceResourceMap.keySet().removeAll(beanNames);
}
private synchronized void registerWorkflow(WorkflowMonitor workflowMonitor)
throws MalformedObjectNameException {
String workflowBeanName = getWorkflowBeanName(workflowMonitor.getWorkflowType());
register(workflowMonitor, getObjectName(workflowBeanName));
}
private synchronized void unregisterWorkflows(Collection<String> workflowMonitors)
throws MalformedObjectNameException {
for (String workflowMonitor : workflowMonitors) {
String workflowBeanName = getWorkflowBeanName(workflowMonitor);
unregister(getObjectName(workflowBeanName));
_perTypeWorkflowMonitorMap.remove(workflowMonitor);
}
}
private synchronized void registerJob(JobMonitor jobMonitor) throws MalformedObjectNameException {
String jobBeanName = getJobBeanName(jobMonitor.getJobType());
register(jobMonitor, getObjectName(jobBeanName));
}
private synchronized void unregisterJobs(Collection<String> jobMonitors)
throws MalformedObjectNameException {
for (String jobMonitor : jobMonitors) {
String jobBeanName = getJobBeanName(jobMonitor);
unregister(getObjectName(jobBeanName));
_perTypeJobMonitorMap.remove(jobMonitor);
}
}
public String clusterBeanName() {
return String.format("%s=%s", CLUSTER_DN_KEY, _clusterName);
}
/**
* Build instance bean name
* @param instanceName
* @return instance bean name
*/
private String getInstanceBeanName(String instanceName) {
return String.format("%s,%s=%s", clusterBeanName(), INSTANCE_DN_KEY, instanceName);
}
/**
* Build resource bean name
* @param resourceName
* @return resource bean name
*/
private String getResourceBeanName(String resourceName) {
return String.format("%s,%s=%s", clusterBeanName(), RESOURCE_DN_KEY, resourceName);
}
/**
* Build per-instance resource bean name:
* "cluster={clusterName},instanceName={instanceName},resourceName={resourceName}"
* @param instanceName
* @param resourceName
* @return per-instance resource bean name
*/
public String getPerInstanceResourceBeanName(String instanceName, String resourceName) {
return String.format("%s,%s", clusterBeanName(), new PerInstanceResourceMonitor.BeanName(
instanceName, resourceName).toString());
}
/**
* Build workflow per type bean name
* "cluster={clusterName},workflowType={workflowType},
* @param workflowType The workflow type
* @return per workflow type bean name
*/
public String getWorkflowBeanName(String workflowType) {
return String.format("%s, %s=%s", clusterBeanName(), WORKFLOW_TYPE_DN_KEY, workflowType);
}
/**
* Build job per type bean name
* "cluster={clusterName},jobType={jobType},
* @param jobType The job type
* @return per job type bean name
*/
public String getJobBeanName(String jobType) {
return String.format("%s, %s=%s", clusterBeanName(), JOB_TYPE_DN_KEY, jobType);
}
@Override
public String getSensorName() {
return CLUSTER_STATUS_KEY + "." + _clusterName;
}
}
| helix-core/src/main/java/org/apache/helix/monitoring/mbeans/ClusterStatusMonitor.java | package org.apache.helix.monitoring.mbeans;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.helix.controller.stages.BestPossibleStateOutput;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.Partition;
import org.apache.helix.model.Resource;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskDriver;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.Workflow;
import org.apache.helix.task.WorkflowConfig;
import org.apache.helix.task.WorkflowContext;
import org.apache.log4j.Logger;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ClusterStatusMonitor implements ClusterStatusMonitorMBean {
private static final Logger LOG = Logger.getLogger(ClusterStatusMonitor.class);
public static final String CLUSTER_STATUS_KEY = "ClusterStatus";
static final String MESSAGE_QUEUE_STATUS_KEY = "MessageQueueStatus";
static final String RESOURCE_STATUS_KEY = "ResourceStatus";
public static final String PARTICIPANT_STATUS_KEY = "ParticipantStatus";
static final String CLUSTER_DN_KEY = "cluster";
static final String RESOURCE_DN_KEY = "resourceName";
static final String INSTANCE_DN_KEY = "instanceName";
static final String MESSAGE_QUEUE_DN_KEY = "messageQueue";
static final String WORKFLOW_TYPE_DN_KEY = "workflowType";
static final String JOB_TYPE_DN_KEY = "jobType";
static final String DEFAULT_WORKFLOW_JOB_TYPE = "DEFAULT";
public static final String DEFAULT_TAG = "DEFAULT";
private final String _clusterName;
private final MBeanServer _beanServer;
private Set<String> _liveInstances = Collections.emptySet();
private Set<String> _instances = Collections.emptySet();
private Set<String> _disabledInstances = Collections.emptySet();
private Map<String, Set<String>> _disabledPartitions = Collections.emptyMap();
private Map<String, Long> _instanceMsgQueueSizes = Maps.newConcurrentMap();
private final ConcurrentHashMap<String, ResourceMonitor> _resourceMbeanMap =
new ConcurrentHashMap<String, ResourceMonitor>();
private final ConcurrentHashMap<String, InstanceMonitor> _instanceMbeanMap =
new ConcurrentHashMap<String, InstanceMonitor>();
/**
* PerInstanceResource bean map: beanName->bean
*/
private final Map<PerInstanceResourceMonitor.BeanName, PerInstanceResourceMonitor> _perInstanceResourceMap =
new ConcurrentHashMap<PerInstanceResourceMonitor.BeanName, PerInstanceResourceMonitor>();
private final Map<String, WorkflowMonitor> _perTypeWorkflowMonitorMap =
new ConcurrentHashMap<String, WorkflowMonitor>();
private final Map<String, JobMonitor> _perTypeJobMonitorMap =
new ConcurrentHashMap<String, JobMonitor>();
public ClusterStatusMonitor(String clusterName) {
_clusterName = clusterName;
_beanServer = ManagementFactory.getPlatformMBeanServer();
try {
register(this, getObjectName(clusterBeanName()));
} catch (Exception e) {
LOG.error("Fail to regiter ClusterStatusMonitor", e);
}
}
public ObjectName getObjectName(String name) throws MalformedObjectNameException {
return new ObjectName(String.format("%s: %s", CLUSTER_STATUS_KEY, name));
}
// TODO remove getBeanName()?
// Used by other external JMX consumers like ingraph
public String getBeanName() {
return CLUSTER_STATUS_KEY + " " + _clusterName;
}
@Override
public long getDownInstanceGauge() {
return _instances.size() - _liveInstances.size();
}
@Override
public long getInstancesGauge() {
return _instances.size();
}
@Override
public long getDisabledInstancesGauge() {
return _disabledInstances.size();
}
@Override
public long getDisabledPartitionsGauge() {
int numDisabled = 0;
for (String instance : _disabledPartitions.keySet()) {
numDisabled += _disabledPartitions.get(instance).size();
}
return numDisabled;
}
@Override
public long getMaxMessageQueueSizeGauge() {
long maxQueueSize = 0;
for (Long queueSize : _instanceMsgQueueSizes.values()) {
if (queueSize > maxQueueSize) {
maxQueueSize = queueSize;
}
}
return maxQueueSize;
}
@Override
public long getInstanceMessageQueueBacklog() {
long sum = 0;
for (Long queueSize : _instanceMsgQueueSizes.values()) {
sum += queueSize;
}
return sum;
}
private void register(Object bean, ObjectName name) {
try {
if (_beanServer.isRegistered(name)) {
_beanServer.unregisterMBean(name);
}
} catch (Exception e) {
// OK
}
try {
LOG.info("Register MBean: " + name);
_beanServer.registerMBean(bean, name);
} catch (Exception e) {
LOG.warn("Could not register MBean: " + name, e);
}
}
private void unregister(ObjectName name) {
try {
if (_beanServer.isRegistered(name)) {
LOG.info("Unregistering " + name.toString());
_beanServer.unregisterMBean(name);
}
} catch (Exception e) {
LOG.warn("Could not unregister MBean: " + name, e);
}
}
/**
* Update the gauges for all instances in the cluster
* @param liveInstanceSet the current set of live instances
* @param instanceSet the current set of configured instances (live or other
* @param disabledInstanceSet the current set of configured instances that are disabled
* @param disabledPartitions a map of instance name to the set of partitions disabled on it
* @param tags a map of instance name to the set of tags on it
*/
public void setClusterInstanceStatus(Set<String> liveInstanceSet, Set<String> instanceSet,
Set<String> disabledInstanceSet, Map<String, Set<String>> disabledPartitions,
Map<String, Set<String>> tags) {
// Unregister beans for instances that are no longer configured
Set<String> toUnregister = Sets.newHashSet(_instanceMbeanMap.keySet());
toUnregister.removeAll(instanceSet);
try {
unregisterInstances(toUnregister);
} catch (MalformedObjectNameException e) {
LOG.error("Could not unregister instances from MBean server: " + toUnregister, e);
}
// Register beans for instances that are newly configured
Set<String> toRegister = Sets.newHashSet(instanceSet);
toRegister.removeAll(_instanceMbeanMap.keySet());
Set<InstanceMonitor> monitorsToRegister = Sets.newHashSet();
for (String instanceName : toRegister) {
InstanceMonitor bean = new InstanceMonitor(_clusterName, instanceName);
bean.updateInstance(tags.get(instanceName), disabledPartitions.get(instanceName),
liveInstanceSet.contains(instanceName), !disabledInstanceSet.contains(instanceName));
monitorsToRegister.add(bean);
}
try {
registerInstances(monitorsToRegister);
} catch (MalformedObjectNameException e) {
LOG.error("Could not register instances with MBean server: " + toRegister, e);
}
// Update all the sets
_instances = instanceSet;
_liveInstances = liveInstanceSet;
_disabledInstances = disabledInstanceSet;
_disabledPartitions = disabledPartitions;
// Update the instance MBeans
for (String instanceName : instanceSet) {
if (_instanceMbeanMap.containsKey(instanceName)) {
// Update the bean
InstanceMonitor bean = _instanceMbeanMap.get(instanceName);
String oldSensorName = bean.getSensorName();
bean.updateInstance(tags.get(instanceName), disabledPartitions.get(instanceName),
liveInstanceSet.contains(instanceName), !disabledInstanceSet.contains(instanceName));
// If the sensor name changed, re-register the bean so that listeners won't miss it
String newSensorName = bean.getSensorName();
if (!oldSensorName.equals(newSensorName)) {
try {
unregisterInstances(Arrays.asList(instanceName));
registerInstances(Arrays.asList(bean));
} catch (MalformedObjectNameException e) {
LOG.error("Could not refresh registration with MBean server: " + instanceName, e);
}
}
}
}
}
/**
* Update gauges for resource at instance level
* @param bestPossibleStates
* @param resourceMap
* @param stateModelDefMap
*/
public void setPerInstanceResourceStatus(BestPossibleStateOutput bestPossibleStates,
Map<String, InstanceConfig> instanceConfigMap, Map<String, Resource> resourceMap,
Map<String, StateModelDefinition> stateModelDefMap) {
// Convert to perInstanceResource beanName->partition->state
Map<PerInstanceResourceMonitor.BeanName, Map<Partition, String>> beanMap =
new HashMap<PerInstanceResourceMonitor.BeanName, Map<Partition, String>>();
for (String resource : bestPossibleStates.resourceSet()) {
Map<Partition, Map<String, String>> partitionStateMap =
bestPossibleStates.getResourceMap(resource);
for (Partition partition : partitionStateMap.keySet()) {
Map<String, String> instanceStateMap = partitionStateMap.get(partition);
for (String instance : instanceStateMap.keySet()) {
String state = instanceStateMap.get(instance);
PerInstanceResourceMonitor.BeanName beanName =
new PerInstanceResourceMonitor.BeanName(instance, resource);
if (!beanMap.containsKey(beanName)) {
beanMap.put(beanName, new HashMap<Partition, String>());
}
beanMap.get(beanName).put(partition, state);
}
}
}
// Unregister beans for per-instance resources that no longer exist
Set<PerInstanceResourceMonitor.BeanName> toUnregister =
Sets.newHashSet(_perInstanceResourceMap.keySet());
toUnregister.removeAll(beanMap.keySet());
try {
unregisterPerInstanceResources(toUnregister);
} catch (MalformedObjectNameException e) {
LOG.error("Fail to unregister per-instance resource from MBean server: " + toUnregister, e);
}
// Register beans for per-instance resources that are newly configured
Set<PerInstanceResourceMonitor.BeanName> toRegister = Sets.newHashSet(beanMap.keySet());
toRegister.removeAll(_perInstanceResourceMap.keySet());
Set<PerInstanceResourceMonitor> monitorsToRegister = Sets.newHashSet();
for (PerInstanceResourceMonitor.BeanName beanName : toRegister) {
PerInstanceResourceMonitor bean =
new PerInstanceResourceMonitor(_clusterName, beanName.instanceName(),
beanName.resourceName());
String stateModelDefName = resourceMap.get(beanName.resourceName()).getStateModelDefRef();
InstanceConfig config = instanceConfigMap.get(beanName.instanceName());
bean.update(beanMap.get(beanName), Sets.newHashSet(config.getTags()),
stateModelDefMap.get(stateModelDefName));
monitorsToRegister.add(bean);
}
try {
registerPerInstanceResources(monitorsToRegister);
} catch (MalformedObjectNameException e) {
LOG.error("Fail to register per-instance resource with MBean server: " + toRegister, e);
}
// Update existing beans
for (PerInstanceResourceMonitor.BeanName beanName : _perInstanceResourceMap.keySet()) {
PerInstanceResourceMonitor bean = _perInstanceResourceMap.get(beanName);
String stateModelDefName = resourceMap.get(beanName.resourceName()).getStateModelDefRef();
InstanceConfig config = instanceConfigMap.get(beanName.instanceName());
bean.update(beanMap.get(beanName), Sets.newHashSet(config.getTags()),
stateModelDefMap.get(stateModelDefName));
}
}
/**
* Indicate that a resource has been dropped, thus making it OK to drop its metrics
* @param resourceName the resource that has been dropped
*/
public void unregisterResource(String resourceName) {
if (_resourceMbeanMap.containsKey(resourceName)) {
synchronized (this) {
if (_resourceMbeanMap.containsKey(resourceName)) {
try {
unregisterResources(Arrays.asList(resourceName));
} catch (MalformedObjectNameException e) {
LOG.error("Could not unregister beans for " + resourceName, e);
}
}
}
}
}
public void setResourceStatus(ExternalView externalView, IdealState idealState,
StateModelDefinition stateModelDef) {
String topState = null;
if (stateModelDef != null) {
List<String> priorityList = stateModelDef.getStatesPriorityList();
if (!priorityList.isEmpty()) {
topState = priorityList.get(0);
}
}
try {
String resourceName = externalView.getId();
if (!_resourceMbeanMap.containsKey(resourceName)) {
synchronized (this) {
if (!_resourceMbeanMap.containsKey(resourceName)) {
ResourceMonitor bean = new ResourceMonitor(_clusterName, resourceName);
bean.updateResource(externalView, idealState, topState);
registerResources(Arrays.asList(bean));
}
}
}
ResourceMonitor bean = _resourceMbeanMap.get(resourceName);
String oldSensorName = bean.getSensorName();
bean.updateResource(externalView, idealState, topState);
String newSensorName = bean.getSensorName();
if (!oldSensorName.equals(newSensorName)) {
unregisterResources(Arrays.asList(resourceName));
registerResources(Arrays.asList(bean));
}
} catch (Exception e) {
LOG.error("Fail to set resource status, resource: " + idealState.getResourceName(), e);
}
}
public void addMessageQueueSize(String instanceName, long msgQueueSize) {
_instanceMsgQueueSizes.put(instanceName, msgQueueSize);
}
public void reset() {
LOG.info("Reset ClusterStatusMonitor");
try {
unregisterResources(_resourceMbeanMap.keySet());
_resourceMbeanMap.clear();
_instanceMsgQueueSizes.clear();
unregisterInstances(_instanceMbeanMap.keySet());
_instanceMbeanMap.clear();
unregisterPerInstanceResources(_perInstanceResourceMap.keySet());
unregister(getObjectName(clusterBeanName()));
unregisterWorkflows(_perTypeWorkflowMonitorMap.keySet());
unregisterJobs(_perTypeJobMonitorMap.keySet());
} catch (Exception e) {
LOG.error("Fail to reset ClusterStatusMonitor, cluster: " + _clusterName, e);
}
}
public void refreshWorkflowsStatus(TaskDriver driver) {
for (WorkflowMonitor workflowMonitor : _perTypeWorkflowMonitorMap.values()) {
workflowMonitor.resetGauges();
}
Map<String, WorkflowConfig> workflowConfigMap = driver.getWorkflows();
for (String workflow : workflowConfigMap.keySet()) {
if (workflowConfigMap.get(workflow).isRecurring()) {
continue;
}
WorkflowContext workflowContext = driver.getWorkflowContext(workflow);
TaskState currentState =
workflowContext == null ? TaskState.NOT_STARTED : workflowContext.getWorkflowState();
updateWorkflowGauges(workflowConfigMap.get(workflow), currentState);
}
}
public void updateWorkflowCounters(WorkflowConfig workflowConfig, TaskState to) {
String workflowType = workflowConfig.getWorkflowType();
workflowType = preProcessWorkflow(workflowType);
_perTypeWorkflowMonitorMap.get(workflowType).updateWorkflowCounters(to);
}
private void updateWorkflowGauges(WorkflowConfig workflowConfig, TaskState current) {
String workflowType = workflowConfig.getWorkflowType();
workflowType = preProcessWorkflow(workflowType);
_perTypeWorkflowMonitorMap.get(workflowType).updateWorkflowGauges(current);
}
private String preProcessWorkflow(String workflowType) {
if (workflowType == null || workflowType.length() == 0) {
workflowType = DEFAULT_WORKFLOW_JOB_TYPE;
}
if (!_perTypeWorkflowMonitorMap.containsKey(workflowType)) {
WorkflowMonitor monitor = new WorkflowMonitor(_clusterName, workflowType);
try {
registerWorkflow(monitor);
} catch (MalformedObjectNameException e) {
LOG.error("Failed to register object for workflow type : " + workflowType, e);
}
_perTypeWorkflowMonitorMap.put(workflowType, monitor);
}
return workflowType;
}
public void refreshJobsStatus(TaskDriver driver) {
for (JobMonitor jobMonitor : _perTypeJobMonitorMap.values()) {
jobMonitor.resetJobGauge();
}
for (String workflow : driver.getWorkflows().keySet()) {
Set<String> allJobs = driver.getWorkflowConfig(workflow).getJobDag().getAllNodes();
WorkflowContext workflowContext = driver.getWorkflowContext(workflow);
for (String job : allJobs) {
TaskState currentState =
workflowContext == null ? TaskState.NOT_STARTED : workflowContext.getJobState(job);
updateJobGauges(driver.getJobConfig(job), currentState);
}
}
}
public void updateJobCounters(JobConfig jobConfig, TaskState to) {
String jobType = jobConfig.getJobType();
jobType = preProcessJobMonitor(jobType);
_perTypeJobMonitorMap.get(jobType).updateJobCounters(to);
}
private void updateJobGauges(JobConfig jobConfig, TaskState current) {
String jobType = jobConfig.getJobType();
jobType = preProcessJobMonitor(jobType);
_perTypeJobMonitorMap.get(jobType).updateJobGauge(current);
}
private String preProcessJobMonitor(String jobType) {
if (jobType == null || jobType.length() == 0) {
jobType = DEFAULT_WORKFLOW_JOB_TYPE;
}
if (!_perTypeJobMonitorMap.containsKey(jobType)) {
JobMonitor monitor = new JobMonitor(_clusterName, jobType);
try {
registerJob(monitor);
} catch (MalformedObjectNameException e) {
LOG.error("Failed to register job type : " + jobType, e);
}
_perTypeJobMonitorMap.put(jobType, monitor);
}
return jobType;
}
private synchronized void registerInstances(Collection<InstanceMonitor> instances)
throws MalformedObjectNameException {
for (InstanceMonitor monitor : instances) {
String instanceName = monitor.getInstanceName();
String beanName = getInstanceBeanName(instanceName);
register(monitor, getObjectName(beanName));
_instanceMbeanMap.put(instanceName, monitor);
}
}
private synchronized void unregisterInstances(Collection<String> instances)
throws MalformedObjectNameException {
for (String instanceName : instances) {
String beanName = getInstanceBeanName(instanceName);
unregister(getObjectName(beanName));
}
_instanceMbeanMap.keySet().removeAll(instances);
}
private synchronized void registerResources(Collection<ResourceMonitor> resources)
throws MalformedObjectNameException {
for (ResourceMonitor monitor : resources) {
String resourceName = monitor.getResourceName();
String beanName = getResourceBeanName(resourceName);
register(monitor, getObjectName(beanName));
_resourceMbeanMap.put(resourceName, monitor);
}
}
private synchronized void unregisterResources(Collection<String> resources)
throws MalformedObjectNameException {
for (String resourceName : resources) {
String beanName = getResourceBeanName(resourceName);
unregister(getObjectName(beanName));
}
_resourceMbeanMap.keySet().removeAll(resources);
}
private synchronized void registerPerInstanceResources(
Collection<PerInstanceResourceMonitor> monitors) throws MalformedObjectNameException {
for (PerInstanceResourceMonitor monitor : monitors) {
String instanceName = monitor.getInstanceName();
String resourceName = monitor.getResourceName();
String beanName = getPerInstanceResourceBeanName(instanceName, resourceName);
register(monitor, getObjectName(beanName));
_perInstanceResourceMap.put(new PerInstanceResourceMonitor.BeanName(instanceName,
resourceName), monitor);
}
}
private synchronized void unregisterPerInstanceResources(
Collection<PerInstanceResourceMonitor.BeanName> beanNames)
throws MalformedObjectNameException {
for (PerInstanceResourceMonitor.BeanName beanName : beanNames) {
unregister(getObjectName(getPerInstanceResourceBeanName(beanName.instanceName(),
beanName.resourceName())));
}
_perInstanceResourceMap.keySet().removeAll(beanNames);
}
private synchronized void registerWorkflow(WorkflowMonitor workflowMonitor)
throws MalformedObjectNameException {
String workflowBeanName = getWorkflowBeanName(workflowMonitor.getWorkflowType());
register(workflowMonitor, getObjectName(workflowBeanName));
}
private synchronized void unregisterWorkflows(Collection<String> workflowMonitors)
throws MalformedObjectNameException {
for (String workflowMonitor : workflowMonitors) {
String workflowBeanName = getWorkflowBeanName(workflowMonitor);
unregister(getObjectName(workflowBeanName));
_perTypeWorkflowMonitorMap.remove(workflowMonitor);
}
}
private synchronized void registerJob(JobMonitor jobMonitor) throws MalformedObjectNameException {
String jobBeanName = getJobBeanName(jobMonitor.getJobType());
register(jobMonitor, getObjectName(jobBeanName));
}
private synchronized void unregisterJobs(Collection<String> jobMonitors)
throws MalformedObjectNameException {
for (String jobMonitor : jobMonitors) {
String jobBeanName = getJobBeanName(jobMonitor);
unregister(getObjectName(jobBeanName));
_perTypeJobMonitorMap.remove(jobMonitor);
}
}
public String clusterBeanName() {
return String.format("%s=%s", CLUSTER_DN_KEY, _clusterName);
}
/**
* Build instance bean name
* @param instanceName
* @return instance bean name
*/
private String getInstanceBeanName(String instanceName) {
return String.format("%s,%s=%s", clusterBeanName(), INSTANCE_DN_KEY, instanceName);
}
/**
* Build resource bean name
* @param resourceName
* @return resource bean name
*/
private String getResourceBeanName(String resourceName) {
return String.format("%s,%s=%s", clusterBeanName(), RESOURCE_DN_KEY, resourceName);
}
/**
* Build per-instance resource bean name:
* "cluster={clusterName},instanceName={instanceName},resourceName={resourceName}"
* @param instanceName
* @param resourceName
* @return per-instance resource bean name
*/
public String getPerInstanceResourceBeanName(String instanceName, String resourceName) {
return String.format("%s,%s", clusterBeanName(), new PerInstanceResourceMonitor.BeanName(
instanceName, resourceName).toString());
}
/**
* Build workflow per type bean name
* "cluster={clusterName},workflowType={workflowType},
* @param workflowType The workflow type
* @return per workflow type bean name
*/
public String getWorkflowBeanName(String workflowType) {
return String.format("%s, %s=%s", clusterBeanName(), WORKFLOW_TYPE_DN_KEY, workflowType);
}
/**
* Build job per type bean name
* "cluster={clusterName},jobType={jobType},
* @param jobType The job type
* @return per job type bean name
*/
public String getJobBeanName(String jobType) {
return String.format("%s, %s=%s", clusterBeanName(), JOB_TYPE_DN_KEY, jobType);
}
@Override
public String getSensorName() {
return CLUSTER_STATUS_KEY + "." + _clusterName;
}
}
| Fix NPE when first time call WorkflowRebalancer
| helix-core/src/main/java/org/apache/helix/monitoring/mbeans/ClusterStatusMonitor.java | Fix NPE when first time call WorkflowRebalancer | <ide><path>elix-core/src/main/java/org/apache/helix/monitoring/mbeans/ClusterStatusMonitor.java
<ide> }
<ide>
<ide> private void updateJobGauges(JobConfig jobConfig, TaskState current) {
<add> // When first time for WorkflowRebalancer call, jobconfig may not ready.
<add> // Thus only check it for gauge.
<add> if (jobConfig == null) {
<add> return;
<add> }
<ide> String jobType = jobConfig.getJobType();
<ide> jobType = preProcessJobMonitor(jobType);
<ide> _perTypeJobMonitorMap.get(jobType).updateJobGauge(current); |
|
Java | mit | 20fc21b3efd70418c477216f440a2fed4d2eb455 | 0 | jugglinmike/es6draft,anba/es6draft,jugglinmike/es6draft,anba/es6draft,jugglinmike/es6draft,jugglinmike/es6draft,anba/es6draft | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.objects.intl;
import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Errors.throwRangeError;
import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError;
import static com.github.anba.es6draft.runtime.types.builtins.ExoticArray.ArrayCreate;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import java.util.AbstractMap.SimpleEntry;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Lazy;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.objects.intl.IntlAbstractOperations.OptionsRecord.MatcherType;
import com.github.anba.es6draft.runtime.objects.intl.LanguageTagParser.LanguageTag;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Type;
import com.ibm.icu.util.LocaleMatcher;
import com.ibm.icu.util.LocalePriorityList;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.TimeZone.SystemTimeZoneType;
import com.ibm.icu.util.ULocale;
/**
* <h1>9 Locale and Parameter Negotiation</h1><br>
* <h2>9.2 Abstract Operations</h2>
*/
public final class IntlAbstractOperations {
private IntlAbstractOperations() {
}
/**
* 6.1 Case Sensitivity and Case Mapping
*/
public static String ToUpperCase(String s) {
char[] ca = s.toCharArray();
for (int i = 0, len = ca.length; i < len; ++i) {
char c = ca[i];
if (c >= 'a' && c <= 'z') {
c = (char) ('A' + (c - 'a'));
}
ca[i] = c;
}
return String.valueOf(ca);
}
/**
* 6.2.1 Unicode Locale Extension Sequences
*/
private static String[] UnicodeLocaleExtSequence(String languageTag) {
unicodeExt: {
if (languageTag.startsWith("x-")) {
// privateuse-only case
break unicodeExt;
}
int indexUnicode = languageTag.indexOf("-u-");
if (indexUnicode == -1) {
// no unicode extension
break unicodeExt;
}
int indexPrivateUse = languageTag.lastIndexOf("-x-", indexUnicode);
if (indexPrivateUse != -1) {
// -u- in privateuse case
break unicodeExt;
}
// found unicode extension, search end index
int endIndex = languageTag.length();
for (int i = indexUnicode + 3;;) {
int sep = languageTag.indexOf('-', i);
if (sep == -1) {
// end of string reached
break;
}
assert sep + 2 < languageTag.length() : languageTag;
if (languageTag.charAt(sep + 2) == '-') {
// next singleton found
endIndex = sep;
break;
}
i = sep + 1;
}
String noExtension = languageTag.substring(0, indexUnicode)
+ languageTag.substring(endIndex);
String extension = languageTag.substring(indexUnicode, endIndex);
return new String[] { noExtension, extension };
}
return new String[] { languageTag, "" };
}
/**
* 6.2.2 IsStructurallyValidLanguageTag (locale)
*/
public static LanguageTag IsStructurallyValidLanguageTag(String locale) {
return new LanguageTagParser(locale).parse();
}
/**
* 6.2.3 CanonicalizeLanguageTag (locale)
*/
public static String CanonicalizeLanguageTag(LanguageTag locale) {
return locale.canonicalize();
}
/**
* 6.2.4 DefaultLocale ()
*/
public static String DefaultLocale(Realm realm) {
return realm.getLocale().toLanguageTag();
}
/**
* 6.3.1 IsWellFormedCurrencyCode (currency)
*/
public static boolean IsWellFormedCurrencyCode(ExecutionContext cx, Object currency) {
String normalized = ToFlatString(cx, currency);
if (normalized.length() != 3) {
return false;
}
return isAlpha(normalized.charAt(0)) && isAlpha(normalized.charAt(1))
&& isAlpha(normalized.charAt(2));
}
private static final boolean isAlpha(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
private static final Set<String> JDK_TIMEZONE_NAMES = set("ACT", "AET", "AGT", "ART", "AST",
"BET", "BST", "CAT", "CNT", "CST", "CTT", "EAT", "ECT", "IET", "IST", "JST", "MIT",
"NET", "NST", "PLT", "PNT", "PRT", "PST", "SST", "VST");
private static final Lazy<Map<String, String>> timezones = new Lazy<Map<String, String>>() {
@Override
protected Map<String, String> computeValue() {
HashMap<String, String> map = new HashMap<>();
Set<String> ids = TimeZone.getAvailableIDs(SystemTimeZoneType.ANY, null, null);
for (String id : ids) {
if (JDK_TIMEZONE_NAMES.contains(id)) {
// ignore non-IANA, JDK-specific timezones
continue;
}
map.put(ToUpperCase(id), id);
}
return map;
}
};
/**
* 6.4.1 IsValidTimeZoneName (timeZone)
*/
public static boolean IsValidTimeZoneName(String timeZone) {
return timezones.get().containsKey(ToUpperCase(timeZone));
}
/**
* 6.4.2 CanonicalizeTimeZoneName (timeZone)
*/
public static String CanonicalizeTimeZoneName(String timeZone) {
/* step 1 */
String ianaTimeZone = timezones.get().get(ToUpperCase(timeZone));
/* step 2 */
ianaTimeZone = TimeZone.getCanonicalID(ianaTimeZone);
assert ianaTimeZone != null : "invalid timezone: " + timeZone;
/* step 3 */
if ("Etc/UTC".equals(ianaTimeZone) || "Etc/GMT".equals(ianaTimeZone)) {
return "UTC";
}
/* step 4 */
return ianaTimeZone;
}
/**
* 6.4.3 DefaultTimeZone ()
*/
public static String DefaultTimeZone(Realm realm) {
return realm.getTimezone().getID();
}
private static final Map<String, String[]> oldStyleLanguageTags;
static {
// generated from CLDR-2.0.0
HashMap<String, String[]> map = new HashMap<>();
map.put("az-Latn-AZ", new String[] { "az-AZ" });
map.put("ha-Latn-GH", new String[] { "ha-GH" });
map.put("ha-Latn-NE", new String[] { "ha-NE" });
map.put("ha-Latn-NG", new String[] { "ha-NG" });
map.put("kk-Cyrl-KZ", new String[] { "kk-KZ" });
map.put("ku-Arab-IQ", new String[] { "ku-IQ" });
map.put("ku-Arab-IR", new String[] { "ku-IR" });
map.put("ku-Latn-SY", new String[] { "ku-SY" });
map.put("ku-Latn-TR", new String[] { "ku-TR" });
map.put("mn-Mong-CN", new String[] { "mn-CN" });
map.put("mn-Cyrl-MN", new String[] { "mn-MN" });
map.put("pa-Guru-IN", new String[] { "pa-IN" });
map.put("pa-Arab-PK", new String[] { "pa-PK" });
map.put("shi-Latn-MA", new String[] { "shi-MA" });
map.put("sr-Latn-BA", new String[] { "sh-BA" });
map.put("sr-Latn-RS", new String[] { "sh-CS", "sh-YU" });
map.put("sr-Cyrl-BA", new String[] { "sr-BA" });
map.put("sr-Cyrl-RS", new String[] { "sr-CS", "sr-RS", "sr-YU" });
map.put("sr-Latn-ME", new String[] { "sr-ME" });
map.put("tg-Cyrl-TJ", new String[] { "tg-TJ" });
map.put("fil-PH", new String[] { "tl-PH" });
map.put("tzm-Latn-MA", new String[] { "tzm-MA" });
map.put("uz-Arab-AF", new String[] { "uz-AF" });
map.put("uz-Cyrl-UZ", new String[] { "uz-UZ" });
map.put("vai-Vaii-LR", new String[] { "vai-LR" });
map.put("zh-Hans-CN", new String[] { "zh-CN" });
map.put("zh-Hant-HK", new String[] { "zh-HK" });
map.put("zh-Hant-MO", new String[] { "zh-MO" });
map.put("zh-Hans-SG", new String[] { "zh-SG" });
map.put("zh-Hant-TW", new String[] { "zh-TW" });
oldStyleLanguageTags = map;
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public static Set<String> GetAvailableLocales(ULocale[] locales) {
Map<String, String[]> oldTags = oldStyleLanguageTags;
HashSet<String> set = new HashSet<>(locales.length);
for (ULocale locale : locales) {
String tag = locale.toLanguageTag();
set.add(tag);
if (oldTags.containsKey(tag)) {
for (String old : oldTags.get(tag)) {
set.add(old);
}
}
}
return set;
}
public enum ExtensionKey {
// Collator
co, kn, kf,
// NumberFormat
nu,
// DateTimeFormat
ca, /* nu */
;
private static ExtensionKey forName(String name, int index) {
assert index + 2 <= name.length();
char c0 = name.charAt(index), c1 = name.charAt(index + 1);
if (c0 == 'c') {
return c1 == 'a' ? ca : c1 == 'o' ? co : null;
}
if (c0 == 'k') {
return c1 == 'f' ? kf : c1 == 'n' ? kn : null;
}
return c0 == 'n' && c1 == 'u' ? nu : null;
}
}
private static EnumMap<ExtensionKey, String> unicodeLocaleExtensions(String extension) {
/*
* http://unicode.org/reports/tr35/#Unicode_locale_identifier
*
* unicode_locale_extensions = sep "u" (1*(sep keyword) / 1*(sep attribute) *(sep keyword))
* keyword = key [sep type]
* key = 2alphanum
* type = 3*8alphanum *(sep 3*8alphanum)
* attribute = 3*8alphanum
*/
final int KEY_LENGTH = 2;
final int SEP_LENGTH = 1;
final int KEY_SEP_LENGTH = KEY_LENGTH + SEP_LENGTH;
assert extension.startsWith("-u-") && extension.length() >= 3 + KEY_LENGTH : extension;
EnumMap<ExtensionKey, String> map = new EnumMap<>(ExtensionKey.class);
ExtensionKey key = null;
int start = 3, startKeyword = start, length = extension.length();
for (int index = start; index < length; ++index) {
char c = extension.charAt(index);
if (c != '-') {
continue;
}
int partLength = index - start;
assert partLength >= KEY_LENGTH;
if (partLength == KEY_LENGTH) {
// found new keyword
if (key != null && !map.containsKey(key)) {
// commit last keyword
int from = startKeyword + KEY_SEP_LENGTH;
int to = start - SEP_LENGTH;
String type = to >= from ? extension.substring(from, to) : "";
map.put(key, type);
}
key = ExtensionKey.forName(extension, start);
startKeyword = start;
}
start = index + 1;
}
boolean trailingKeyword = length - start == KEY_LENGTH;
if (key != null && !map.containsKey(key)) {
// commit last keyword
int from = startKeyword + KEY_SEP_LENGTH;
int to = trailingKeyword ? start - SEP_LENGTH : length;
String type = to >= from ? extension.substring(from, to) : "";
map.put(key, type);
}
if (trailingKeyword) {
key = ExtensionKey.forName(extension, start);
if (key != null && !map.containsKey(key)) {
map.put(key, "");
}
}
return map;
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public interface LocaleData {
LocaleDataInfo info(ULocale locale);
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public interface LocaleDataInfo {
/**
* Returns {@link #entries(IntlAbstractOperations.ExtensionKey)}.get(0)
*/
String defaultValue(ExtensionKey extensionKey);
/**
* Returns [[sortLocaleData]], [[searchLocaleData]] or [[localeData]]
*/
List<String> entries(ExtensionKey extensionKey);
}
/**
* 9.2.1 CanonicalizeLocaleList (locales)
*/
public static Set<String> CanonicalizeLocaleList(ExecutionContext cx, Object locales) {
if (Type.isUndefined(locales)) {
return emptySet();
}
if (Type.isString(locales)) {
// handle the string-only case directly
String tag = ToFlatString(cx, locales);
LanguageTag langTag = IsStructurallyValidLanguageTag(tag);
if (langTag == null) {
throw throwRangeError(cx, Messages.Key.IntlStructurallyInvalidLanguageTag, tag);
}
tag = CanonicalizeLanguageTag(langTag);
return singleton(tag);
}
Set<String> seen = new LinkedHashSet<>();
ScriptObject o = ToObject(cx, locales);
Object lenValue = Get(cx, o, "length");
long len = ToUint32(cx, lenValue);
for (long k = 0; k < len; ++k) {
String pk = ToString(k);
boolean kPresent = HasProperty(cx, o, pk);
if (kPresent) {
Object kValue = Get(cx, o, pk);
if (!(Type.isString(kValue) || Type.isObject(pk))) {
throwTypeError(cx, Messages.Key.IncompatibleObject);
}
String tag = ToFlatString(cx, kValue);
LanguageTag langTag = IsStructurallyValidLanguageTag(tag);
if (langTag == null) {
throw throwRangeError(cx, Messages.Key.IntlStructurallyInvalidLanguageTag, tag);
}
tag = CanonicalizeLanguageTag(langTag);
if (!seen.contains(tag)) {
seen.add(tag);
}
}
}
return seen;
}
/**
* 9.2.2 BestAvailableLocale (availableLocales, locale)
*/
public static String BestAvailableLocale(Set<String> availableLocales, String locale) {
String candidate = locale;
while (true) {
if (availableLocales.contains(candidate)) {
return candidate;
}
int pos = candidate.lastIndexOf('-');
if (pos == -1) {
return null;
}
if (pos >= 2 && candidate.charAt(pos - 2) == '-') {
pos -= 2;
}
candidate = candidate.substring(0, pos);
}
}
private static final class LocaleMatch {
String locale;
String extension;
int extensionIndex;
}
/**
* 9.2.3 LookupMatcher (availableLocales, requestedLocales)
*/
public static LocaleMatch LookupMatcher(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales) {
for (String locale : requestedLocales) {
String[] unicodeExt = UnicodeLocaleExtSequence(locale);
String noExtensionsLocale = unicodeExt[0];
String availableLocale = BestAvailableLocale(availableLocales.get(), noExtensionsLocale);
if (availableLocale != null) {
return LookupMatch(availableLocale, locale, unicodeExt);
}
}
return LookupMatch(DefaultLocale(cx.getRealm()), null, null);
}
private static LocaleMatch LookupMatch(String availableLocale, String locale,
String[] unicodeExt) {
LocaleMatch result = new LocaleMatch();
result.locale = availableLocale;
if (locale != null && !locale.equals(unicodeExt[0])) {
result.extension = unicodeExt[1];
result.extensionIndex = locale.indexOf("-u-") + 2;
}
return result;
}
/**
* 9.2.4 BestFitMatcher (availableLocales, requestedLocales)
*/
public static LocaleMatch BestFitMatcher(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales) {
// fast path when no specific locale was requested
if (requestedLocales.isEmpty()) {
final String defaultLocale = DefaultLocale(cx.getRealm());
return BestFitMatch(defaultLocale, defaultLocale);
}
LocaleMatcher matcher = CreateDefaultMatcher();
Map<String, Entry<ULocale, ULocale>> map = GetMaximizedLocales(matcher,
availableLocales.get());
final String defaultLocale = DefaultLocale(cx.getRealm());
// `BEST_FIT_MIN_MATCH - epsilon` to ensure match is at least BEST_FIT_MIN_MATCH to be
// considered 'best-fit'
final double initialWeight = BEST_FIT_MIN_MATCH - Double.MIN_VALUE;
// search for best match, start with default locale and initial weight
String bestMatchCandidate = defaultLocale;
Entry<String, Double> bestMatch = new SimpleEntry<>(defaultLocale, initialWeight);
for (String locale : requestedLocales) {
String[] unicodeExt = UnicodeLocaleExtSequence(locale);
String noExtensionsLocale = unicodeExt[0];
Entry<String, Double> match = BestFitAvailableLocale(matcher, map, noExtensionsLocale);
if (match.getValue() > bestMatch.getValue()) {
bestMatch = match;
bestMatchCandidate = locale;
}
}
return BestFitMatch(bestMatch.getKey(), bestMatchCandidate);
}
private static LocaleMatch BestFitMatch(String locale, String bestMatchCandidate) {
LocaleMatch result = new LocaleMatch();
result.locale = locale;
String[] unicodeExt = UnicodeLocaleExtSequence(bestMatchCandidate);
String noExtensionsLocale = unicodeExt[0];
if (!bestMatchCandidate.equals(noExtensionsLocale)) {
result.extension = unicodeExt[1];
result.extensionIndex = bestMatchCandidate.indexOf("-u-") + 2;
}
return result;
}
/**
* Minimum match value for best fit matcher, currently set to 0.5 to match ICU4J's defaults
*/
private static final double BEST_FIT_MIN_MATCH = 0.5;
private static LocaleMatcher CreateDefaultMatcher() {
LocalePriorityList priorityList = LocalePriorityList.add(ULocale.ROOT).build();
@SuppressWarnings("deprecation")
LocaleMatcher matcher = new LocaleMatcher(priorityList, languageMatchData);
return matcher;
}
/**
* language matcher data shipped with current ICU4J is outdated, use data from CLDR 23 instead
*
* TODO: remove when ICU4J is updated
*/
@SuppressWarnings("deprecation")
private static final LocaleMatcher.LanguageMatcherData languageMatchData = new LocaleMatcher.LanguageMatcherData()
/* @formatter:off */
.addDistance("no", "nb", 100, false)
.addDistance("nn", "nb", 96, false)
.addDistance("nn", "no", 96, false)
.addDistance("da", "no", 90, false)
.addDistance("da", "nb", 90, false)
.addDistance("hr", "bs", 96, false)
.addDistance("sh", "bs", 96, false)
.addDistance("sr", "bs", 96, false)
.addDistance("sh", "hr", 96, false)
.addDistance("sr", "hr", 96, false)
.addDistance("sh", "sr", 96, false)
.addDistance("ms", "id", 90, false)
.addDistance("ssy", "aa", 96, false)
.addDistance("sr-Latn", "sr-Cyrl", 90, false)
.addDistance("*-Hans", "*-Hant", 85, true)
.addDistance("*-Hant", "*-Hans", 75, true)
.addDistance("gsw-*-*", "de-*-CH", 85, true) // changed from "desired=gsw, supported=de-CH"
.addDistance("gsw", "de", 80, true)
.addDistance("en-*-US", "en-*-CA", 98, false)
.addDistance("en-*-US", "en-*-*", 97, false)
.addDistance("en-*-CA", "en-*-*", 98, false)
.addDistance("en-*-*", "en-*-*", 99, false)
.addDistance("es-*-ES", "es-*-ES", 100, false)
.addDistance("es-*-ES", "es-*-*", 93, false)
.addDistance("*", "*", 1, false)
.addDistance("*-*", "*-*", 20, false)
.addDistance("*-*-*", "*-*-*", 96, false)
.freeze();
/* @formatter:on */
/**
* Hard cache for this entries to reduce time required to finish intl-tests
*/
private static final Map<String, Entry<ULocale, ULocale>> maximizedLocales = new ConcurrentHashMap<>();
private static Map<String, Entry<ULocale, ULocale>> GetMaximizedLocales(LocaleMatcher matcher,
Set<String> availableLocales) {
Map<String, Entry<ULocale, ULocale>> map = new LinkedHashMap<>();
for (String available : availableLocales) {
Entry<ULocale, ULocale> entry = maximizedLocales.get(available);
if (entry == null) {
ULocale canonicalized = matcher.canonicalize(ULocale.forLanguageTag(available));
ULocale maximized = addLikelySubtagsWithDefaults(canonicalized);
entry = new SimpleEntry<>(canonicalized, maximized);
maximizedLocales.put(available, entry);
}
map.put(available, entry);
}
return map;
}
private static Entry<String, Double> BestFitAvailableLocale(LocaleMatcher matcher,
Map<String, Entry<ULocale, ULocale>> availableLocales, String requestedLocale) {
ULocale canonicalized = matcher.canonicalize(ULocale.forLanguageTag(requestedLocale));
ULocale maximized = addLikelySubtagsWithDefaults(canonicalized);
String bestMatchLocale = null;
Entry<ULocale, ULocale> bestMatchEntry = null;
double bestMatch = Double.NEGATIVE_INFINITY;
for (Entry<String, Entry<ULocale, ULocale>> available : availableLocales.entrySet()) {
Entry<ULocale, ULocale> entry = available.getValue();
double match = matcher
.match(canonicalized, maximized, entry.getKey(), entry.getValue());
// if (match > 0.90) {
// System.out.printf("[%s; %s, %s] -> [%s; %s, %s] => %f\n", requestedLocale,
// canonicalized, maximized, available.getKey(), entry.getKey(), entry.getValue(),
// match);
// }
if (match > bestMatch
|| (match == bestMatch && isBetterMatch(canonicalized, maximized,
bestMatchEntry, entry))) {
bestMatchLocale = available.getKey();
bestMatchEntry = entry;
bestMatch = match;
}
}
return new SimpleEntry<>(bestMatchLocale, bestMatch);
}
/**
* Requests for "en-US" gives two results with '1.0' score:
* <ul>
* <li>[en; en, en_Latn_US]
* <li>[en-US; en_US, en_Latn_US]
* </ul>
* Obviously it's the latter result we're interested in.
*/
private static boolean isBetterMatch(ULocale canonicalized, ULocale maximized,
Entry<ULocale, ULocale> oldMatch, Entry<ULocale, ULocale> newMatch) {
// prefer more detailled information over less
ULocale oldCanonicalized = oldMatch.getKey();
ULocale newCanonicalized = newMatch.getKey();
String language = canonicalized.getLanguage();
if (newCanonicalized.getLanguage().equals(language)
&& !oldCanonicalized.getLanguage().equals(language)) {
return true;
}
String script = canonicalized.getScript();
if (newCanonicalized.getScript().equals(script)
&& !oldCanonicalized.getScript().equals(script)) {
return true;
}
String region = canonicalized.getCountry();
if (newCanonicalized.getCountry().equals(region)
&& !oldCanonicalized.getCountry().equals(region)) {
return true;
}
return false;
}
private static ULocale addLikelySubtagsWithDefaults(ULocale locale) {
ULocale maximized = ULocale.addLikelySubtags(locale);
if (maximized == locale) {
// already in maximal form, or no data available for maximization, just make sure
// language, script and region are not undefined (ICU4J expects all are defined)
String language = locale.getLanguage();
String script = locale.getScript();
String region = locale.getCountry();
if (language.isEmpty() || script.isEmpty() || region.isEmpty()) {
language = !language.isEmpty() ? language : "und";
script = !script.isEmpty() ? script : "Zzzz";
region = !region.isEmpty() ? region : "ZZ";
return new ULocale(language, script, region);
}
}
return maximized;
}
public static final class OptionsRecord {
public enum MatcherType {
Lookup, BestFit;
public static MatcherType forName(String name) {
switch (name) {
case "lookup":
return Lookup;
case "best fit":
return BestFit;
default:
throw new IllegalArgumentException(name);
}
}
}
public MatcherType localeMatcher = MatcherType.BestFit;
public EnumMap<ExtensionKey, String> values = new EnumMap<>(ExtensionKey.class);
}
public static final class ResolvedLocale {
public String dataLocale;
public String locale;
public EnumMap<ExtensionKey, String> values = new EnumMap<>(ExtensionKey.class);
}
/**
* 9.2.5 ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys,
* localeData)
*/
public static ResolvedLocale ResolveLocale(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales,
OptionsRecord options, List<ExtensionKey> relevantExtensionKeys, LocaleData localeData) {
/* steps 1-3 */
MatcherType matcher = options.localeMatcher;
LocaleMatch r;
if (matcher == MatcherType.Lookup) {
r = LookupMatcher(cx, availableLocales, requestedLocales);
} else {
r = BestFitMatcher(cx, availableLocales, requestedLocales);
}
/* step 4 */
String foundLocale = r.locale;
LocaleDataInfo foundLocaleData = localeData.info(ULocale.forLanguageTag(foundLocale));
/* step 5 */
// List<String> extensionSubtags = null;
EnumMap<ExtensionKey, String> extensionSubtags = null;
if (r.extension != null) {
String extension = r.extension;
// extensionSubtags = Arrays.asList(extension.split("-"));
extensionSubtags = unicodeLocaleExtensions(extension);
}
/* steps 6-7 */
ResolvedLocale result = new ResolvedLocale();
result.dataLocale = foundLocale;
// fast path for steps 8-14
if (extensionSubtags == null && options.values.isEmpty()) {
/* steps 8-11 */
for (int i = 0, len = relevantExtensionKeys.size(); i < len; ++i) {
ExtensionKey key = relevantExtensionKeys.get(i);
String value = foundLocaleData.defaultValue(key);
result.values.put(key, value);
}
/* step 12 (not applicable) */
/* step 13 */
result.locale = foundLocale;
/* step 14 */
return result;
}
/* steps 8-11 */
String supportedExtension = "-u";
for (int i = 0, len = relevantExtensionKeys.size(); i < len; ++i) {
ExtensionKey key = relevantExtensionKeys.get(i);
List<String> keyLocaleData = foundLocaleData.entries(key);
String value = keyLocaleData.get(0);
String supportedExtensionAddition = "";
if (extensionSubtags != null) {
// int keyPos = extensionSubtags.indexOf(key.name());
if (extensionSubtags.containsKey(key)) {
if (!extensionSubtags.get(key).isEmpty()) {
String requestedValue = extensionSubtags.get(key);
int valuePos = keyLocaleData.indexOf(requestedValue);
if (valuePos != -1) {
value = requestedValue;
supportedExtensionAddition = "-" + key.name() + "-" + value;
}
} else {
int valuePos = keyLocaleData.indexOf("true");
if (valuePos != -1) {
value = "true";
}
}
}
}
if (options.values.containsKey(key)) {
String optionsValue = options.values.get(key);
if (keyLocaleData.indexOf(optionsValue) != -1) {
if (!optionsValue.equals(value)) {
value = optionsValue;
supportedExtensionAddition = "";
}
}
}
result.values.put(key, value);
supportedExtension += supportedExtensionAddition;
}
/* step 12 */
if (supportedExtension.length() > 2) {
assert r.extension != null;
int extensionIndex = r.extensionIndex;
extensionIndex = Math.min(extensionIndex, foundLocale.length());
String preExtension = foundLocale.substring(0, extensionIndex);
String postExtension = foundLocale.substring(extensionIndex);
foundLocale = preExtension + supportedExtension + postExtension;
}
/* step 13 */
result.locale = foundLocale;
/* step 14 */
return result;
}
/**
* 9.2.6 LookupSupportedLocales (availableLocales, requestedLocales)
*/
public static List<String> LookupSupportedLocales(ExecutionContext cx,
Set<String> availableLocales, Set<String> requestedLocales) {
List<String> subset = new ArrayList<>();
for (String locale : requestedLocales) {
String noExtensionsLocale = UnicodeLocaleExtSequence(locale)[0];
String availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);
if (availableLocale != null) {
subset.add(locale);
}
}
return subset;
}
/**
* 9.2.7 BestFitSupportedLocales (availableLocales, requestedLocales)
*/
public static List<String> BestFitSupportedLocales(ExecutionContext cx,
Set<String> availableLocales, Set<String> requestedLocales) {
LocaleMatcher matcher = CreateDefaultMatcher();
Map<String, Entry<ULocale, ULocale>> map = GetMaximizedLocales(matcher, availableLocales);
List<String> subset = new ArrayList<>();
for (String locale : requestedLocales) {
String noExtensionsLocale = UnicodeLocaleExtSequence(locale)[0];
Entry<String, Double> availableLocale = BestFitAvailableLocale(matcher, map,
noExtensionsLocale);
if (availableLocale.getValue() >= BEST_FIT_MIN_MATCH) {
subset.add(locale);
}
}
return subset;
}
/**
* 9.2.8 SupportedLocales (availableLocales, requestedLocales, options)
*/
public static ScriptObject SupportedLocales(ExecutionContext cx, Set<String> availableLocales,
Set<String> requestedLocales, Object options) {
String matcher = null;
if (!Type.isUndefined(options)) {
ScriptObject opts = ToObject(cx, options);
// FIXME: spec issue? algorithm steps should use abstract operation GetOption()
matcher = GetStringOption(cx, opts, "localeMatcher", set("lookup", "best fit"),
"best fit");
}
List<String> subset;
if (matcher == null || "best fit".equals(matcher)) {
subset = BestFitSupportedLocales(cx, availableLocales, requestedLocales);
} else {
subset = LookupSupportedLocales(cx, availableLocales, requestedLocales);
}
ScriptObject array = ArrayCreate(cx, subset.size());
for (int i = 0, size = subset.size(); i < size; ++i) {
String key = Integer.toString(i);
Object value = subset.get(i);
DefinePropertyOrThrow(cx, array, key, new PropertyDescriptor(value, false, true, false));
}
PropertyDescriptor nonConfigurableWritable = new PropertyDescriptor();
nonConfigurableWritable.setConfigurable(false);
nonConfigurableWritable.setWritable(false);
DefinePropertyOrThrow(cx, array, "length", nonConfigurableWritable);
return array;
}
/**
* 9.2.9 GetOption (options, property, type, values, fallback)
*/
public static String GetStringOption(ExecutionContext cx, ScriptObject options,
String property, Set<String> values, String fallback) {
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
String val = ToFlatString(cx, value);
if (values != null && !values.contains(val)) {
throwRangeError(cx, Messages.Key.IntlInvalidOption, val);
}
return val;
}
return fallback;
}
/**
* 9.2.9 GetOption (options, property, type, values, fallback)
*/
public static Boolean GetBooleanOption(ExecutionContext cx, ScriptObject options,
String property, Boolean fallback) {
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
return ToBoolean(value);
}
return fallback;
}
/**
* 9.2.10 GetNumberOption (options, property, minimum, maximum, fallback)
*/
public static int GetNumberOption(ExecutionContext cx, ScriptObject options, String property,
int minimum, int maximum, int fallback) {
assert minimum <= maximum;
assert minimum <= fallback && fallback <= maximum;
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
double val = ToNumber(cx, value);
if (Double.isNaN(val) || val < minimum || val > maximum) {
throwRangeError(cx, Messages.Key.IntlInvalidOption, Double.toString(val));
}
return (int) Math.floor(val);
}
return fallback;
}
@SafeVarargs
private static <T> Set<T> set(T... elements) {
return new HashSet<>(Arrays.asList(elements));
}
}
| src/main/java/com/github/anba/es6draft/runtime/objects/intl/IntlAbstractOperations.java | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.objects.intl;
import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Errors.throwRangeError;
import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError;
import static com.github.anba.es6draft.runtime.types.builtins.ExoticArray.ArrayCreate;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import java.util.AbstractMap.SimpleEntry;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Lazy;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.objects.intl.IntlAbstractOperations.OptionsRecord.MatcherType;
import com.github.anba.es6draft.runtime.objects.intl.LanguageTagParser.LanguageTag;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Type;
import com.ibm.icu.util.LocaleMatcher;
import com.ibm.icu.util.LocalePriorityList;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.TimeZone.SystemTimeZoneType;
import com.ibm.icu.util.ULocale;
/**
* <h1>9 Locale and Parameter Negotiation</h1><br>
* <h2>9.2 Abstract Operations</h2>
*/
public final class IntlAbstractOperations {
private IntlAbstractOperations() {
}
/**
* 6.1 Case Sensitivity and Case Mapping
*/
public static String ToUpperCase(String s) {
char[] ca = s.toCharArray();
for (int i = 0, len = ca.length; i < len; ++i) {
char c = ca[i];
if (c >= 'a' && c <= 'z') {
c = (char) ('A' + (c - 'a'));
}
ca[i] = c;
}
return String.valueOf(ca);
}
/**
* 6.2.1 Unicode Locale Extension Sequences
*/
private static String[] UnicodeLocaleExtSequence(String languageTag) {
unicodeExt: {
if (languageTag.startsWith("x-")) {
// privateuse-only case
break unicodeExt;
}
int indexUnicode = languageTag.indexOf("-u-");
if (indexUnicode == -1) {
// no unicode extension
break unicodeExt;
}
int indexPrivateUse = languageTag.lastIndexOf("-x-", indexUnicode);
if (indexPrivateUse != -1) {
// -u- in privateuse case
break unicodeExt;
}
// found unicode extension, search end index
int endIndex = languageTag.length();
for (int i = indexUnicode + 3;;) {
int sep = languageTag.indexOf('-', i);
if (sep == -1) {
// end of string reached
break;
}
assert sep + 2 < languageTag.length() : languageTag;
if (languageTag.charAt(sep + 2) == '-') {
// next singleton found
endIndex = sep;
break;
}
i = sep + 1;
}
String noExtension = languageTag.substring(0, indexUnicode)
+ languageTag.substring(endIndex);
String extension = languageTag.substring(indexUnicode, endIndex);
return new String[] { noExtension, extension };
}
return new String[] { languageTag, "" };
}
/**
* 6.2.2 IsStructurallyValidLanguageTag (locale)
*/
public static LanguageTag IsStructurallyValidLanguageTag(String locale) {
return new LanguageTagParser(locale).parse();
}
/**
* 6.2.3 CanonicalizeLanguageTag (locale)
*/
public static String CanonicalizeLanguageTag(LanguageTag locale) {
return locale.canonicalize();
}
/**
* 6.2.4 DefaultLocale ()
*/
public static String DefaultLocale(Realm realm) {
return realm.getLocale().toLanguageTag();
}
/**
* 6.3.1 IsWellFormedCurrencyCode (currency)
*/
public static boolean IsWellFormedCurrencyCode(ExecutionContext cx, Object currency) {
String normalized = ToFlatString(cx, currency);
if (normalized.length() != 3) {
return false;
}
return isAlpha(normalized.charAt(0)) && isAlpha(normalized.charAt(1))
&& isAlpha(normalized.charAt(2));
}
private static final boolean isAlpha(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
private static final Set<String> JDK_TIMEZONE_NAMES = set("ACT", "AET", "AGT", "ART", "AST",
"BET", "BST", "CAT", "CNT", "CST", "CTT", "EAT", "ECT", "IET", "IST", "JST", "MIT",
"NET", "NST", "PLT", "PNT", "PRT", "PST", "SST", "VST");
private static final Lazy<Map<String, String>> timezones = new Lazy<Map<String, String>>() {
@Override
protected Map<String, String> computeValue() {
HashMap<String, String> map = new HashMap<>();
Set<String> ids = TimeZone.getAvailableIDs(SystemTimeZoneType.ANY, null, null);
for (String id : ids) {
if (JDK_TIMEZONE_NAMES.contains(id)) {
// ignore non-IANA, JDK-specific timezones
continue;
}
map.put(ToUpperCase(id), id);
}
return map;
}
};
/**
* 6.4.1 IsValidTimeZoneName (timeZone)
*/
public static boolean IsValidTimeZoneName(String timeZone) {
return timezones.get().containsKey(ToUpperCase(timeZone));
}
/**
* 6.4.2 CanonicalizeTimeZoneName (timeZone)
*/
public static String CanonicalizeTimeZoneName(String timeZone) {
/* step 1 */
String ianaTimeZone = timezones.get().get(ToUpperCase(timeZone));
/* step 2 */
ianaTimeZone = TimeZone.getCanonicalID(ianaTimeZone);
assert ianaTimeZone != null : "invalid timezone: " + timeZone;
/* step 3 */
if ("Etc/UTC".equals(ianaTimeZone) || "Etc/GMT".equals(ianaTimeZone)) {
return "UTC";
}
/* step 4 */
return ianaTimeZone;
}
/**
* 6.4.3 DefaultTimeZone ()
*/
public static String DefaultTimeZone(Realm realm) {
return realm.getTimezone().getID();
}
private static final Map<String, String[]> oldStyleLanguageTags;
static {
// generated from CLDR-2.0.0
HashMap<String, String[]> map = new HashMap<>();
map.put("az-Latn-AZ", new String[] { "az-AZ" });
map.put("ha-Latn-GH", new String[] { "ha-GH" });
map.put("ha-Latn-NE", new String[] { "ha-NE" });
map.put("ha-Latn-NG", new String[] { "ha-NG" });
map.put("kk-Cyrl-KZ", new String[] { "kk-KZ" });
map.put("ku-Arab-IQ", new String[] { "ku-IQ" });
map.put("ku-Arab-IR", new String[] { "ku-IR" });
map.put("ku-Latn-SY", new String[] { "ku-SY" });
map.put("ku-Latn-TR", new String[] { "ku-TR" });
map.put("mn-Mong-CN", new String[] { "mn-CN" });
map.put("mn-Cyrl-MN", new String[] { "mn-MN" });
map.put("pa-Guru-IN", new String[] { "pa-IN" });
map.put("pa-Arab-PK", new String[] { "pa-PK" });
map.put("shi-Latn-MA", new String[] { "shi-MA" });
map.put("sr-Latn-BA", new String[] { "sh-BA" });
map.put("sr-Latn-RS", new String[] { "sh-CS", "sh-YU" });
map.put("sr-Cyrl-BA", new String[] { "sr-BA" });
map.put("sr-Cyrl-RS", new String[] { "sr-CS", "sr-RS", "sr-YU" });
map.put("sr-Latn-ME", new String[] { "sr-ME" });
map.put("tg-Cyrl-TJ", new String[] { "tg-TJ" });
map.put("fil-PH", new String[] { "tl-PH" });
map.put("tzm-Latn-MA", new String[] { "tzm-MA" });
map.put("uz-Arab-AF", new String[] { "uz-AF" });
map.put("uz-Cyrl-UZ", new String[] { "uz-UZ" });
map.put("vai-Vaii-LR", new String[] { "vai-LR" });
map.put("zh-Hans-CN", new String[] { "zh-CN" });
map.put("zh-Hant-HK", new String[] { "zh-HK" });
map.put("zh-Hant-MO", new String[] { "zh-MO" });
map.put("zh-Hans-SG", new String[] { "zh-SG" });
map.put("zh-Hant-TW", new String[] { "zh-TW" });
oldStyleLanguageTags = map;
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public static Set<String> GetAvailableLocales(ULocale[] locales) {
Map<String, String[]> oldTags = oldStyleLanguageTags;
HashSet<String> set = new HashSet<>(locales.length);
for (ULocale locale : locales) {
String tag = locale.toLanguageTag();
set.add(tag);
if (oldTags.containsKey(tag)) {
for (String old : oldTags.get(tag)) {
set.add(old);
}
}
}
return set;
}
public enum ExtensionKey {
// Collator
co, kn, kf,
// NumberFormat
nu,
// DateTimeFormat
ca, /* nu */
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public interface LocaleData {
LocaleDataInfo info(ULocale locale);
}
/**
* 9.1 Internal Properties of Service Constructors
*/
public interface LocaleDataInfo {
/**
* Returns {@link #entries(ExtensionKey)}.get(0)
*/
String defaultValue(ExtensionKey extensionKey);
/**
* Returns [sortLocaleData]], [[searchLocaleData]] or [[localeData]]
*/
List<String> entries(ExtensionKey extensionKey);
}
/**
* 9.2.1 CanonicalizeLocaleList (locales)
*/
public static Set<String> CanonicalizeLocaleList(ExecutionContext cx, Object locales) {
if (Type.isUndefined(locales)) {
return emptySet();
}
if (Type.isString(locales)) {
// handle the string-only case directly
String tag = ToFlatString(cx, locales);
LanguageTag langTag = IsStructurallyValidLanguageTag(tag);
if (langTag == null) {
throw throwRangeError(cx, Messages.Key.IntlStructurallyInvalidLanguageTag, tag);
}
tag = CanonicalizeLanguageTag(langTag);
return singleton(tag);
}
Set<String> seen = new LinkedHashSet<>();
ScriptObject o = ToObject(cx, locales);
Object lenValue = Get(cx, o, "length");
long len = ToUint32(cx, lenValue);
for (long k = 0; k < len; ++k) {
String pk = ToString(k);
boolean kPresent = HasProperty(cx, o, pk);
if (kPresent) {
Object kValue = Get(cx, o, pk);
if (!(Type.isString(kValue) || Type.isObject(pk))) {
throwTypeError(cx, Messages.Key.IncompatibleObject);
}
String tag = ToFlatString(cx, kValue);
LanguageTag langTag = IsStructurallyValidLanguageTag(tag);
if (langTag == null) {
throw throwRangeError(cx, Messages.Key.IntlStructurallyInvalidLanguageTag, tag);
}
tag = CanonicalizeLanguageTag(langTag);
if (!seen.contains(tag)) {
seen.add(tag);
}
}
}
return seen;
}
/**
* 9.2.2 BestAvailableLocale (availableLocales, locale)
*/
public static String BestAvailableLocale(Set<String> availableLocales, String locale) {
String candidate = locale;
while (true) {
if (availableLocales.contains(candidate)) {
return candidate;
}
int pos = candidate.lastIndexOf('-');
if (pos == -1) {
return null;
}
if (pos >= 2 && candidate.charAt(pos - 2) == '-') {
pos -= 2;
}
candidate = candidate.substring(0, pos);
}
}
private static final class LocaleMatch {
String locale;
String extension;
int extensionIndex;
}
/**
* 9.2.3 LookupMatcher (availableLocales, requestedLocales)
*/
public static LocaleMatch LookupMatcher(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales) {
for (String locale : requestedLocales) {
String[] unicodeExt = UnicodeLocaleExtSequence(locale);
String noExtensionsLocale = unicodeExt[0];
String availableLocale = BestAvailableLocale(availableLocales.get(), noExtensionsLocale);
if (availableLocale != null) {
return LookupMatch(availableLocale, locale, unicodeExt);
}
}
return LookupMatch(DefaultLocale(cx.getRealm()), null, null);
}
private static LocaleMatch LookupMatch(String availableLocale, String locale,
String[] unicodeExt) {
LocaleMatch result = new LocaleMatch();
result.locale = availableLocale;
if (locale != null && !locale.equals(unicodeExt[0])) {
result.extension = unicodeExt[1];
result.extensionIndex = locale.indexOf("-u-") + 2;
}
return result;
}
/**
* 9.2.4 BestFitMatcher (availableLocales, requestedLocales)
*/
public static LocaleMatch BestFitMatcher(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales) {
// fast path when no specific locale was requested
if (requestedLocales.isEmpty()) {
final String defaultLocale = DefaultLocale(cx.getRealm());
return BestFitMatch(defaultLocale, defaultLocale);
}
LocaleMatcher matcher = CreateDefaultMatcher();
Map<String, Entry<ULocale, ULocale>> map = GetMaximizedLocales(matcher,
availableLocales.get());
final String defaultLocale = DefaultLocale(cx.getRealm());
// `BEST_FIT_MIN_MATCH - epsilon` to ensure match is at least BEST_FIT_MIN_MATCH to be
// considered 'best-fit'
final double initialWeight = BEST_FIT_MIN_MATCH - Double.MIN_VALUE;
// search for best match, start with default locale and initial weight
String bestMatchCandidate = defaultLocale;
Entry<String, Double> bestMatch = new SimpleEntry<>(defaultLocale, initialWeight);
for (String locale : requestedLocales) {
String[] unicodeExt = UnicodeLocaleExtSequence(locale);
String noExtensionsLocale = unicodeExt[0];
Entry<String, Double> match = BestFitAvailableLocale(matcher, map, noExtensionsLocale);
if (match.getValue() > bestMatch.getValue()) {
bestMatch = match;
bestMatchCandidate = locale;
}
}
return BestFitMatch(bestMatch.getKey(), bestMatchCandidate);
}
private static LocaleMatch BestFitMatch(String locale, String bestMatchCandidate) {
LocaleMatch result = new LocaleMatch();
result.locale = locale;
String[] unicodeExt = UnicodeLocaleExtSequence(bestMatchCandidate);
String noExtensionsLocale = unicodeExt[0];
if (!bestMatchCandidate.equals(noExtensionsLocale)) {
result.extension = unicodeExt[1];
result.extensionIndex = bestMatchCandidate.indexOf("-u-") + 2;
}
return result;
}
/**
* Minimum match value for best fit matcher, currently set to 0.5 to match ICU4J's defaults
*/
private static final double BEST_FIT_MIN_MATCH = 0.5;
private static LocaleMatcher CreateDefaultMatcher() {
LocalePriorityList priorityList = LocalePriorityList.add(ULocale.ROOT).build();
@SuppressWarnings("deprecation")
LocaleMatcher matcher = new LocaleMatcher(priorityList, languageMatchData);
return matcher;
}
/**
* language matcher data shipped with current ICU4J is outdated, use data from CLDR 23 instead
*
* TODO: remove when ICU4J is updated
*/
@SuppressWarnings("deprecation")
private static final LocaleMatcher.LanguageMatcherData languageMatchData = new LocaleMatcher.LanguageMatcherData()
/* @formatter:off */
.addDistance("no", "nb", 100, false)
.addDistance("nn", "nb", 96, false)
.addDistance("nn", "no", 96, false)
.addDistance("da", "no", 90, false)
.addDistance("da", "nb", 90, false)
.addDistance("hr", "bs", 96, false)
.addDistance("sh", "bs", 96, false)
.addDistance("sr", "bs", 96, false)
.addDistance("sh", "hr", 96, false)
.addDistance("sr", "hr", 96, false)
.addDistance("sh", "sr", 96, false)
.addDistance("ms", "id", 90, false)
.addDistance("ssy", "aa", 96, false)
.addDistance("sr-Latn", "sr-Cyrl", 90, false)
.addDistance("*-Hans", "*-Hant", 85, true)
.addDistance("*-Hant", "*-Hans", 75, true)
.addDistance("gsw-*-*", "de-*-CH", 85, true) // changed from "desired=gsw, supported=de-CH"
.addDistance("gsw", "de", 80, true)
.addDistance("en-*-US", "en-*-CA", 98, false)
.addDistance("en-*-US", "en-*-*", 97, false)
.addDistance("en-*-CA", "en-*-*", 98, false)
.addDistance("en-*-*", "en-*-*", 99, false)
.addDistance("es-*-ES", "es-*-ES", 100, false)
.addDistance("es-*-ES", "es-*-*", 93, false)
.addDistance("*", "*", 1, false)
.addDistance("*-*", "*-*", 20, false)
.addDistance("*-*-*", "*-*-*", 96, false)
.freeze();
/* @formatter:on */
/**
* Hard cache for this entries to reduce time required to finish intl-tests
*/
private static final Map<String, Entry<ULocale, ULocale>> maximizedLocales = new ConcurrentHashMap<>();
private static Map<String, Entry<ULocale, ULocale>> GetMaximizedLocales(LocaleMatcher matcher,
Set<String> availableLocales) {
Map<String, Entry<ULocale, ULocale>> map = new LinkedHashMap<>();
for (String available : availableLocales) {
Entry<ULocale, ULocale> entry = maximizedLocales.get(available);
if (entry == null) {
ULocale canonicalized = matcher.canonicalize(ULocale.forLanguageTag(available));
ULocale maximized = addLikelySubtagsWithDefaults(canonicalized);
entry = new SimpleEntry<>(canonicalized, maximized);
maximizedLocales.put(available, entry);
}
map.put(available, entry);
}
return map;
}
private static Entry<String, Double> BestFitAvailableLocale(LocaleMatcher matcher,
Map<String, Entry<ULocale, ULocale>> availableLocales, String requestedLocale) {
ULocale canonicalized = matcher.canonicalize(ULocale.forLanguageTag(requestedLocale));
ULocale maximized = addLikelySubtagsWithDefaults(canonicalized);
String bestMatchLocale = null;
Entry<ULocale, ULocale> bestMatchEntry = null;
double bestMatch = Double.NEGATIVE_INFINITY;
for (Entry<String, Entry<ULocale, ULocale>> available : availableLocales.entrySet()) {
Entry<ULocale, ULocale> entry = available.getValue();
double match = matcher
.match(canonicalized, maximized, entry.getKey(), entry.getValue());
// if (match > 0.90) {
// System.out.printf("[%s; %s, %s] -> [%s; %s, %s] => %f\n", requestedLocale,
// canonicalized, maximized, available.getKey(), entry.getKey(), entry.getValue(),
// match);
// }
if (match > bestMatch
|| (match == bestMatch && isBetterMatch(canonicalized, maximized,
bestMatchEntry, entry))) {
bestMatchLocale = available.getKey();
bestMatchEntry = entry;
bestMatch = match;
}
}
return new SimpleEntry<>(bestMatchLocale, bestMatch);
}
/**
* Requests for "en-US" gives two results with '1.0' score:
* <ul>
* <li>[en; en, en_Latn_US]
* <li>[en-US; en_US, en_Latn_US]
* </ul>
* Obviously it's the latter result we're interested in.
*/
private static boolean isBetterMatch(ULocale canonicalized, ULocale maximized,
Entry<ULocale, ULocale> oldMatch, Entry<ULocale, ULocale> newMatch) {
// prefer more detailled information over less
ULocale oldCanonicalized = oldMatch.getKey();
ULocale newCanonicalized = newMatch.getKey();
String language = canonicalized.getLanguage();
if (newCanonicalized.getLanguage().equals(language)
&& !oldCanonicalized.getLanguage().equals(language)) {
return true;
}
String script = canonicalized.getScript();
if (newCanonicalized.getScript().equals(script)
&& !oldCanonicalized.getScript().equals(script)) {
return true;
}
String region = canonicalized.getCountry();
if (newCanonicalized.getCountry().equals(region)
&& !oldCanonicalized.getCountry().equals(region)) {
return true;
}
return false;
}
private static ULocale addLikelySubtagsWithDefaults(ULocale locale) {
ULocale maximized = ULocale.addLikelySubtags(locale);
if (maximized == locale) {
// already in maximal form, or no data available for maximization, just make sure
// language, script and region are not undefined (ICU4J expects all are defined)
String language = locale.getLanguage();
String script = locale.getScript();
String region = locale.getCountry();
if (language.isEmpty() || script.isEmpty() || region.isEmpty()) {
language = !language.isEmpty() ? language : "und";
script = !script.isEmpty() ? script : "Zzzz";
region = !region.isEmpty() ? region : "ZZ";
return new ULocale(language, script, region);
}
}
return maximized;
}
public static final class OptionsRecord {
public enum MatcherType {
Lookup, BestFit;
public static MatcherType forName(String name) {
switch (name) {
case "lookup":
return Lookup;
case "best fit":
return BestFit;
default:
throw new IllegalArgumentException(name);
}
}
}
public MatcherType localeMatcher = MatcherType.BestFit;
public EnumMap<ExtensionKey, String> values = new EnumMap<>(ExtensionKey.class);
}
public static final class ResolvedLocale {
public String dataLocale;
public String locale;
public EnumMap<ExtensionKey, String> values = new EnumMap<>(ExtensionKey.class);
}
/**
* 9.2.5 ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys,
* localeData)
*/
public static ResolvedLocale ResolveLocale(ExecutionContext cx,
Lazy<Set<String>> availableLocales, Set<String> requestedLocales,
OptionsRecord options, List<ExtensionKey> relevantExtensionKeys, LocaleData localeData) {
/* steps 1-3 */
MatcherType matcher = options.localeMatcher;
LocaleMatch r;
if (matcher == MatcherType.Lookup) {
r = LookupMatcher(cx, availableLocales, requestedLocales);
} else {
r = BestFitMatcher(cx, availableLocales, requestedLocales);
}
/* step 4 */
String foundLocale = r.locale;
LocaleDataInfo foundLocaleData = localeData.info(ULocale.forLanguageTag(foundLocale));
/* step 5 */
List<String> extensionSubtags = null;
if (r.extension != null) {
String extension = r.extension;
extensionSubtags = Arrays.asList(extension.split("-"));
}
/* steps 6-7 */
ResolvedLocale result = new ResolvedLocale();
result.dataLocale = foundLocale;
// fast path for steps 8-14
if (extensionSubtags == null && options.values.isEmpty()) {
/* steps 8-11 */
for (int i = 0, len = relevantExtensionKeys.size(); i < len; ++i) {
ExtensionKey key = relevantExtensionKeys.get(i);
String value = foundLocaleData.defaultValue(key);
result.values.put(key, value);
}
/* step 12 (not applicable) */
/* step 13 */
result.locale = foundLocale;
/* step 14 */
return result;
}
/* steps 8-11 */
String supportedExtension = "-u";
for (int i = 0, len = relevantExtensionKeys.size(); i < len; ++i) {
ExtensionKey key = relevantExtensionKeys.get(i);
List<String> keyLocaleData = foundLocaleData.entries(key);
String value = keyLocaleData.get(0);
String supportedExtensionAddition = "";
if (extensionSubtags != null) {
int keyPos = extensionSubtags.indexOf(key.name());
if (keyPos != -1) {
if (keyPos + 1 < extensionSubtags.size()
&& extensionSubtags.get(keyPos + 1).length() > 2) {
String requestedValue = extensionSubtags.get(keyPos + 1);
int valuePos = keyLocaleData.indexOf(requestedValue);
if (valuePos != -1) {
value = requestedValue;
supportedExtensionAddition = "-" + key.name() + "-" + value;
}
} else {
int valuePos = keyLocaleData.indexOf("true");
if (valuePos != -1) {
value = "true";
}
}
}
}
if (options.values.containsKey(key)) {
String optionsValue = options.values.get(key);
if (keyLocaleData.indexOf(optionsValue) != -1) {
if (!optionsValue.equals(value)) {
value = optionsValue;
supportedExtensionAddition = "";
}
}
}
result.values.put(key, value);
supportedExtension += supportedExtensionAddition;
}
/* step 12 */
if (supportedExtension.length() > 2) {
assert r.extension != null;
int extensionIndex = r.extensionIndex;
extensionIndex = Math.min(extensionIndex, foundLocale.length());
String preExtension = foundLocale.substring(0, extensionIndex);
String postExtension = foundLocale.substring(extensionIndex);
foundLocale = preExtension + supportedExtension + postExtension;
}
/* step 13 */
result.locale = foundLocale;
/* step 14 */
return result;
}
/**
* 9.2.6 LookupSupportedLocales (availableLocales, requestedLocales)
*/
public static List<String> LookupSupportedLocales(ExecutionContext cx,
Set<String> availableLocales, Set<String> requestedLocales) {
List<String> subset = new ArrayList<>();
for (String locale : requestedLocales) {
String noExtensionsLocale = UnicodeLocaleExtSequence(locale)[0];
String availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);
if (availableLocale != null) {
subset.add(locale);
}
}
return subset;
}
/**
* 9.2.7 BestFitSupportedLocales (availableLocales, requestedLocales)
*/
public static List<String> BestFitSupportedLocales(ExecutionContext cx,
Set<String> availableLocales, Set<String> requestedLocales) {
LocaleMatcher matcher = CreateDefaultMatcher();
Map<String, Entry<ULocale, ULocale>> map = GetMaximizedLocales(matcher, availableLocales);
List<String> subset = new ArrayList<>();
for (String locale : requestedLocales) {
String noExtensionsLocale = UnicodeLocaleExtSequence(locale)[0];
Entry<String, Double> availableLocale = BestFitAvailableLocale(matcher, map,
noExtensionsLocale);
if (availableLocale.getValue() >= BEST_FIT_MIN_MATCH) {
subset.add(locale);
}
}
return subset;
}
/**
* 9.2.8 SupportedLocales (availableLocales, requestedLocales, options)
*/
public static ScriptObject SupportedLocales(ExecutionContext cx, Set<String> availableLocales,
Set<String> requestedLocales, Object options) {
String matcher = null;
if (!Type.isUndefined(options)) {
ScriptObject opts = ToObject(cx, options);
// FIXME: spec issue? algorithm steps should use abstract operation GetOption()
matcher = GetStringOption(cx, opts, "localeMatcher", set("lookup", "best fit"),
"best fit");
}
List<String> subset;
if (matcher == null || "best fit".equals(matcher)) {
subset = BestFitSupportedLocales(cx, availableLocales, requestedLocales);
} else {
subset = LookupSupportedLocales(cx, availableLocales, requestedLocales);
}
ScriptObject array = ArrayCreate(cx, subset.size());
for (int i = 0, size = subset.size(); i < size; ++i) {
String key = Integer.toString(i);
Object value = subset.get(i);
DefinePropertyOrThrow(cx, array, key, new PropertyDescriptor(value, false, true, false));
}
PropertyDescriptor nonConfigurableWritable = new PropertyDescriptor();
nonConfigurableWritable.setConfigurable(false);
nonConfigurableWritable.setWritable(false);
DefinePropertyOrThrow(cx, array, "length", nonConfigurableWritable);
return array;
}
/**
* 9.2.9 GetOption (options, property, type, values, fallback)
*/
public static String GetStringOption(ExecutionContext cx, ScriptObject options,
String property, Set<String> values, String fallback) {
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
String val = ToFlatString(cx, value);
if (values != null && !values.contains(val)) {
throwRangeError(cx, Messages.Key.IntlInvalidOption, val);
}
return val;
}
return fallback;
}
/**
* 9.2.9 GetOption (options, property, type, values, fallback)
*/
public static Boolean GetBooleanOption(ExecutionContext cx, ScriptObject options,
String property, Boolean fallback) {
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
return ToBoolean(value);
}
return fallback;
}
/**
* 9.2.10 GetNumberOption (options, property, minimum, maximum, fallback)
*/
public static int GetNumberOption(ExecutionContext cx, ScriptObject options, String property,
int minimum, int maximum, int fallback) {
assert minimum <= maximum;
assert minimum <= fallback && fallback <= maximum;
Object value = Get(cx, options, property);
if (!Type.isUndefined(value)) {
double val = ToNumber(cx, value);
if (Double.isNaN(val) || val < minimum || val > maximum) {
throwRangeError(cx, Messages.Key.IntlInvalidOption, Double.toString(val));
}
return (int) Math.floor(val);
}
return fallback;
}
@SafeVarargs
private static <T> Set<T> set(T... elements) {
return new HashSet<>(Arrays.asList(elements));
}
}
| add workaround for https://bugs.ecmascript.org/show_bug.cgi?id=2081
| src/main/java/com/github/anba/es6draft/runtime/objects/intl/IntlAbstractOperations.java | add workaround for https://bugs.ecmascript.org/show_bug.cgi?id=2081 | <ide><path>rc/main/java/com/github/anba/es6draft/runtime/objects/intl/IntlAbstractOperations.java
<ide> nu,
<ide> // DateTimeFormat
<ide> ca, /* nu */
<add> ;
<add>
<add> private static ExtensionKey forName(String name, int index) {
<add> assert index + 2 <= name.length();
<add> char c0 = name.charAt(index), c1 = name.charAt(index + 1);
<add> if (c0 == 'c') {
<add> return c1 == 'a' ? ca : c1 == 'o' ? co : null;
<add> }
<add> if (c0 == 'k') {
<add> return c1 == 'f' ? kf : c1 == 'n' ? kn : null;
<add> }
<add> return c0 == 'n' && c1 == 'u' ? nu : null;
<add> }
<add> }
<add>
<add> private static EnumMap<ExtensionKey, String> unicodeLocaleExtensions(String extension) {
<add> /*
<add> * http://unicode.org/reports/tr35/#Unicode_locale_identifier
<add> *
<add> * unicode_locale_extensions = sep "u" (1*(sep keyword) / 1*(sep attribute) *(sep keyword))
<add> * keyword = key [sep type]
<add> * key = 2alphanum
<add> * type = 3*8alphanum *(sep 3*8alphanum)
<add> * attribute = 3*8alphanum
<add> */
<add> final int KEY_LENGTH = 2;
<add> final int SEP_LENGTH = 1;
<add> final int KEY_SEP_LENGTH = KEY_LENGTH + SEP_LENGTH;
<add>
<add> assert extension.startsWith("-u-") && extension.length() >= 3 + KEY_LENGTH : extension;
<add> EnumMap<ExtensionKey, String> map = new EnumMap<>(ExtensionKey.class);
<add> ExtensionKey key = null;
<add> int start = 3, startKeyword = start, length = extension.length();
<add> for (int index = start; index < length; ++index) {
<add> char c = extension.charAt(index);
<add> if (c != '-') {
<add> continue;
<add> }
<add> int partLength = index - start;
<add> assert partLength >= KEY_LENGTH;
<add> if (partLength == KEY_LENGTH) {
<add> // found new keyword
<add> if (key != null && !map.containsKey(key)) {
<add> // commit last keyword
<add> int from = startKeyword + KEY_SEP_LENGTH;
<add> int to = start - SEP_LENGTH;
<add> String type = to >= from ? extension.substring(from, to) : "";
<add> map.put(key, type);
<add> }
<add> key = ExtensionKey.forName(extension, start);
<add> startKeyword = start;
<add> }
<add> start = index + 1;
<add> }
<add> boolean trailingKeyword = length - start == KEY_LENGTH;
<add> if (key != null && !map.containsKey(key)) {
<add> // commit last keyword
<add> int from = startKeyword + KEY_SEP_LENGTH;
<add> int to = trailingKeyword ? start - SEP_LENGTH : length;
<add> String type = to >= from ? extension.substring(from, to) : "";
<add> map.put(key, type);
<add> }
<add> if (trailingKeyword) {
<add> key = ExtensionKey.forName(extension, start);
<add> if (key != null && !map.containsKey(key)) {
<add> map.put(key, "");
<add> }
<add> }
<add> return map;
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public interface LocaleDataInfo {
<ide> /**
<del> * Returns {@link #entries(ExtensionKey)}.get(0)
<add> * Returns {@link #entries(IntlAbstractOperations.ExtensionKey)}.get(0)
<ide> */
<ide> String defaultValue(ExtensionKey extensionKey);
<ide>
<ide> /**
<del> * Returns [sortLocaleData]], [[searchLocaleData]] or [[localeData]]
<add> * Returns [[sortLocaleData]], [[searchLocaleData]] or [[localeData]]
<ide> */
<ide> List<String> entries(ExtensionKey extensionKey);
<ide> }
<ide> String foundLocale = r.locale;
<ide> LocaleDataInfo foundLocaleData = localeData.info(ULocale.forLanguageTag(foundLocale));
<ide> /* step 5 */
<del> List<String> extensionSubtags = null;
<add> // List<String> extensionSubtags = null;
<add> EnumMap<ExtensionKey, String> extensionSubtags = null;
<ide> if (r.extension != null) {
<ide> String extension = r.extension;
<del> extensionSubtags = Arrays.asList(extension.split("-"));
<add> // extensionSubtags = Arrays.asList(extension.split("-"));
<add> extensionSubtags = unicodeLocaleExtensions(extension);
<ide> }
<ide> /* steps 6-7 */
<ide> ResolvedLocale result = new ResolvedLocale();
<ide> String value = keyLocaleData.get(0);
<ide> String supportedExtensionAddition = "";
<ide> if (extensionSubtags != null) {
<del> int keyPos = extensionSubtags.indexOf(key.name());
<del> if (keyPos != -1) {
<del> if (keyPos + 1 < extensionSubtags.size()
<del> && extensionSubtags.get(keyPos + 1).length() > 2) {
<del> String requestedValue = extensionSubtags.get(keyPos + 1);
<add> // int keyPos = extensionSubtags.indexOf(key.name());
<add> if (extensionSubtags.containsKey(key)) {
<add> if (!extensionSubtags.get(key).isEmpty()) {
<add> String requestedValue = extensionSubtags.get(key);
<ide> int valuePos = keyLocaleData.indexOf(requestedValue);
<ide> if (valuePos != -1) {
<ide> value = requestedValue; |
|
Java | agpl-3.0 | 5178097e5adb6b2cca648e5a31bb7329630f4630 | 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 | 4dc7df70-2e62-11e5-9284-b827eb9e62be | hello.java | 4dc27116-2e62-11e5-9284-b827eb9e62be | 4dc7df70-2e62-11e5-9284-b827eb9e62be | hello.java | 4dc7df70-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>4dc27116-2e62-11e5-9284-b827eb9e62be
<add>4dc7df70-2e62-11e5-9284-b827eb9e62be |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.